Polly如何在c#项目中使用

发布时间:2021-03-23 14:48:09 作者:Leah
来源:亿速云 阅读:342

今天就跟大家聊聊有关Polly如何在c#项目中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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

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

// 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()

看完上述内容,你们对Polly如何在c#项目中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. 如如何使用journalctl命令?
  2. 如何在C#项目中使用out与ref参数

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

polly

上一篇:怎么在C语言中对字符串与各数值类型进行转换

下一篇:怎么在docker中使用命令启用多个端口映射

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》