c# 如何更简单的使用Polly

Polly是一个C#实现的弹性瞬时错误处理库
它可以帮助我们做一些容错模式处理,比如:

  • 超时与重试(Timeout and Retry)
  • 熔断器(Circuit Breaker)
  • 舱壁隔离(Bulkhead Isolation)
  • 回退(Fallback)

使用也是非常简单的,比如:

// Retry multiple times, calling an action on each retry
// with the current exception and retry count
Policy
 .Handle<SomeExceptionType>()
 .Retry(3, onRetry: (exception, retryCount) =>
 {
 // Add logic to be executed before each retry, such as logging
 });

但是每个地方我们都得这样写,个人还是不喜,
那么怎么简化呢?
当然是使用 Norns.Urd 这些AOP框架封装我们常用的东西做成 Attribute 啦

如何实现简化呢?

我们来尝试将 Retry功能 做成 RetryAttribute吧

1.安装 AOP 框架

自己写多累呀,用现成的多好呀

dotnet add package Norns.Urd

2.编写 Retry InterceptorAttribute

 public class RetryAttribute : AbstractInterceptorAttribute
 {
 private readonly int retryCount;

 public RetryAttribute(int retryCount)
 {
  this.retryCount = retryCount;
 }

 public override async Task InvokeAsync(AspectContext context, AsyncAspectDelegate next)
 {
  await Policy.Handle<Exception>()
  .RetryAsync(retryCount)
  .ExecuteAsync(() => next(context));
 }
 }

3.考虑到 async 和 sync 在Polly 有差异,那么我们兼容一下吧

 public class RetryAttribute : AbstractInterceptorAttribute
 {
 private readonly int retryCount;

 public RetryAttribute(int retryCount)
 {
  this.retryCount = retryCount;
 }

 public override void Invoke(AspectContext context, AspectDelegate next)
 {
  Policy.Handle<Exception>()
  .Retry(retryCount)
  .Execute(() => next(context));
 }

 public override async Task InvokeAsync(AspectContext context, AsyncAspectDelegate next)
 {
  await Policy.Handle<Exception>()
  .RetryAsync(retryCount)
  .ExecuteAsync(() => next(context));
 }
 }

4.我们来做个测试吧

 public class RetryTest
 {
 public class DoRetryTest
 {
  public int Count { get; set; }

  [Retry(2)] // 使用 Retry
  public virtual void Do()
  {
  if (Count < 50)
  {
   Count++; // 每调用一次就加1
   throw new FieldAccessException();
  }
  }
 }

 public DoRetryTest Mock()
 {
  return new ServiceCollection()
  .AddTransient<DoRetryTest>()
  .ConfigureAop()
  .BuildServiceProvider()
  .GetRequiredService<DoRetryTest>();
 }

 [Fact]
 public void RetryWhenSync()
 {
  var sut = Mock();
  Assert.Throws<FieldAccessException>(() => sut.Do());
  Assert.Equal(3, sut.Count); //我们期望调用总共 3 次
 }
 }

是的,就是这样,我们可以在任何地方使用 RetryAttribute

当然,一些常见的方法已经封装在了 Norns.Urd.Extensions.Polly

这里通过Norns.Urd将Polly的各种功能集成为更加方便使用的功能

如何启用 Norns.Urd + Polly, 只需使用EnablePolly()

如:

new ServiceCollection()
 .AddTransient<DoTimeoutTest>()
 .ConfigureAop(i => i.EnablePolly())

TimeoutAttribute

[Timeout(seconds: 1)] // timeout 1 seconds, when timeout will throw TimeoutRejectedException
double Wait(double seconds);

[Timeout(timeSpan: "00:00:00.100")] // timeout 100 milliseconds, only work on async method when no CancellationToken
async Task<double> WaitAsync(double seconds, CancellationToken cancellationToken = default);

[Timeout(timeSpan: "00:00:01")] // timeout 1 seconds, but no work on async method when no CancellationToken
async Task<double> NoCancellationTokenWaitAsync(double seconds);

RetryAttribute

[Retry(retryCount: 2, ExceptionType = typeof(AccessViolationException))] // retry 2 times when if throw Exception
void Do()

CircuitBreakerAttribute

[CircuitBreaker(exceptionsAllowedBeforeBreaking: 3, durationOfBreak: "00:00:01")]
//or
[AdvancedCircuitBreaker(failureThreshold: 0.1, samplingDuration: "00:00:01", minimumThroughput: 3, durationOfBreak: "00:00:01")]
void Do()

BulkheadAttribute

[Bulkhead(maxParallelization: 5, maxQueuingActions: 10)]
void Do()

有关 Norns.Urd, 大家可以查看 https://fs7744.github.io/Norns.Urd/zh-cn/index.html

以上就是c# 如何更简单的使用Polly的详细内容,更多关于c# 使用Polly的资料请关注我们其它相关文章!

(0)

相关推荐

  • c#基于winform制作音乐播放器

    前言:项目是c#的winform 写的,使用的播放器是基于AxWindowsMediaPlayer. AxWindowsMediaPlayer的方法 1 首先新建一个页面 如图所示: 图片左侧是列表 使用listview 右侧是背景图片.图片框框的地方是后面可以实现的,+和-按钮分别代表添加文件和删除文件 还有就是控制播放的顺序.下面的分别是修改歌词的字体 和展示/隐藏 2 新建一个透明的歌词页面[窗体] 3 新建一个半透明的页面[窗体] 4 业务代码 using System; using S

  • c# HttpClient设置超时的步骤

    HttpClient作为官方推荐的http客户端,相比之前的WebClient和WebRequest好用了很多,但默认无法为每个请求单独设置超时,只能给HttpClient设置默认超时,使用起来不太方便. 声明:本文主要是翻译自THOMAS LEVESQUE'S .NET BLOG的文章:Better timeout handling with HttpClient. 由于工作原因,需要用c#,就语法层而言,c#确实比java优秀,一些库接口封装也更方便简洁.特别是HttpClient,结合了t

  • c# 如何实现自动更新程序

    主要功能介绍 实现文件的自动更新.主要功能: 支持整包完全更新,即客户端只需输入一个服务器地址,即可下载所有文件. 支持增量更新,即只更新指定的某几个文件. 支持自动更新程序的更新 更新界面如图: 客户端 main方法入口 /// <summary> /// 应用程序的主入口点. /// </summary> [STAThread] static void Main() { //在主程序中 更新替换自动升级程序 //ReplaceAutoUpgrade(); bool isEnte

  • c#调用c语言dll需要注意的地方

    一.将C#工程和C的dll工程放在同一个解决方案下,这样就可以实现联动调试,直接从C#中进入C的dll函数里.注意:每次更改dll中的代码后都必须重新生成dll.另,C#与C中有几种变量类型不对应,注意声明时的区分. 语言 C# C 类型 long long long/__int64 byte/Byte unsigned char char wchar_t UInt32 size_t 二.dll工程中头文件加入以下代码: // 此代码为了方便头文件在dll工程和调用该dll的工程中重复利用 //

  • c# 如何对网络信息进行相关设置(ip,dns,网关等)

    网络的相关设置在项目开发中有较多的应用,有时候需要在项目中对网络信息进行相关设置. 现在提供提供几种相关的辅助方法类. (1).IP地址 /// <summary> /// IP地址 /// </summary> public string IpAddress { get { string ipAddress; var address = GetAddress(); if (address == null) { ipAddress = string.Empty; } else {

  • C#调用C类型dll入参为struct的问题详解

    前言 C# 可以通过 DllImport 的方式引用 C 类型的 dll.但很多 dll 的参数不会是简单的基础类型,而是结构体 struct .因此就需要在 C# 端定义同样的结构体类型,才能实现调用 C 类型 dll.这里例举几种不同的结构体情况,以及其对应的解决方案. 基础调用方式 对于一个结构体类型: typedef struct DATA { int nNumber; float fDecimal; }; 在 C# 端就需要定义为 [StructLayout(LayoutKind.Se

  • C# 使用SHA1算法对密码进行加密

    C#中如何使用SHA1对密码进行加密呢?先声明一下,对于编程小编在这个方面还是个小白,如果小编有说的不对的地方,请各位大佬联系小编,小编好进行修改.好了不说废话了上图.在这里呢小编创建的是ASP.NET Web 项目应用程序,winform窗体应用也是可以的 创建好项目之后再你的项目里创建一个类 第二步 在你创建好的类里边先把登录的方法写好,让后再定义一个密加密的方法请看图 第三步在写好加密方法后在你的登录验证方法里面调用你的加密方法就可以了具体调用的代码请看下图 完成上边的操作后你再去你登录按

  • c# 如何自己实现一个ORM框架

    0. 前言 在之前的几篇内容中,我们了解了如何通过ADO.NET 访问数据库,如何修改.新增数据.如何通过DataSet和DataAdapter获取数据,我们将在这一篇试试自己实现一个简单的ORM框架或者说ORM工具类. 涉及到的知识点: 反射(初级) ADO.NET 已有知识 1. ORM 那么,问题来了,什么是ORM?ORM全称 Object Relational Mapping,翻译过来就是对象关系映射.是一种通过描述对象与数据库之间映射关系的数据,将对象保存到数据库中的技术. 在C#中,

  • C#飞机打字游戏的代码示例(winform版)

    游戏界面 程序代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; namesp

  • 使用 BenchmarkDotNet 对 C# 代码进行基准测试

    BenchmarkDotNet 是一个轻量级,开源的,强大的 .NET 工具包,它可以将你的方法转化为基准并跟踪这些方法,最后对这些方法的性能提供一些测试报告,使用 BenchmarkDotNet 玩 基准测试 是非常容易的. 你可以利用 BenchmarkDotNet 在 .NET Framework 和 .NET Core 应用程序上实现基准测试,在这篇文章中,我们将会讨论如何在 .NET Core 中实现基准测试. 安装 BenchmarkDotNet 要想使用 BenchmarkDotN

  • C# TreeView从数据库绑定数据的示例

    封装成一个函数,方便直接调用 //绑定TrreView private void InitModuleTree(DataTable dt) { //清空treeview上所有节点 this.tree_Role.Nodes.Clear(); int[] gen = new int[dt.Rows.Count]; //用于存储父节点Tag int[] zi = new int[dt.Rows.Count]; //用于存储子节点Tag for (int i = 0; i < gen.Length; i

随机推荐