c# 如何更简单的使用Polly

 更新时间:2021年03月23日 10:56:03   作者:victor.x.qu  
这篇文章主要介绍了c# 如何更简单的使用Polly,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

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的资料请关注脚本之家其它相关文章!

相关文章

  • 基于动态修改App.Config与web.Config的使用详解

    基于动态修改App.Config与web.Config的使用详解

    本篇文章是对动态修改App.Config与web.Config的使用进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • C#使用private font改变PDF文件的字体详解

    C#使用private font改变PDF文件的字体详解

    这篇文章主要给大家介绍了关于C#使用private font改变PDF文件的字体的相关资料,文中通过示例代码以及图片介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07
  • asp.net(c#)编程实现将彩色图片变灰阶图片的方法示例

    asp.net(c#)编程实现将彩色图片变灰阶图片的方法示例

    这篇文章主要介绍了asp.net(c#)编程实现将彩色图片变灰阶图片的方法,结合实例形式分析了C#图片读取及属性操作相关技巧,需要的朋友可以参考下
    2017-07-07
  • C#实现Zip压缩目录中所有文件的方法

    C#实现Zip压缩目录中所有文件的方法

    这篇文章主要介绍了C#实现Zip压缩目录中所有文件的方法,涉及C#针对文件的读写与zip压缩相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • WPF基础教程之元素绑定详解

    WPF基础教程之元素绑定详解

    这篇文章主要给大家介绍了关于WPF基础教程之元素绑定的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-01-01
  • C#使用DllImport调用非托管的代码的方法

    C#使用DllImport调用非托管的代码的方法

    C#调用非托管代码的方式主要有Com调用、DllImport方式调用、加载非托管动态链接库、直接执行机器码等方式。现在介绍一下我自己常用的DllImport方式调用MSDN中提到的GetShortPathName方法;
    2013-03-03
  • C#浅拷贝和深拷贝实例解析

    C#浅拷贝和深拷贝实例解析

    这篇文章主要介绍了C#浅拷贝和深拷贝,是比较重要的概念,需要的朋友可以参考下
    2014-08-08
  • C#结束进程及子进程

    C#结束进程及子进程

    这篇文章介绍了C#操作结束进程及子进程的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • c# linq的差集,并集,交集,去重代码(分享)

    c# linq的差集,并集,交集,去重代码(分享)

    下面小编就为大家分享一篇c# linq的差集,并集,交集,去重代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-11-11
  • c#自定义泛型类的实现

    c#自定义泛型类的实现

    本篇文章是对c#中自定义泛型类的实现方法进行了详细的分析介绍,需要的朋友参考下
    2013-05-05

最新评论