c# 如何更简单的使用Polly
作者:victor.x.qu 发布时间:2022-10-24 11:27:46
标签:c#,Polly
目录
如何实现简化呢?
当然,一些常见的方法已经封装在了 Norns.Urd.Extensions.Polly
如何启用 Norns.Urd + Polly, 只需使用EnablePolly()
TimeoutAttribute
RetryAttribute
CircuitBreakerAttribute
BulkheadAttribute
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
来源:https://www.cnblogs.com/fs7744/p/14129076.html


猜你喜欢
- 题目:求100之内的素数方法一:package airthmatic;public class demo8 { /** * 素数是指因数只有
- 一、编译步骤解压下载的GDAL源程序,并在命令行中切换到解压目录。tar -xzvf gdal-2.1.3.tar.gzcd gdal-2.
- 前言有时候我们会在属性注入的时候添加@Lazy注解实现延迟注入,今天咱们通过阅读源码来分析下原因一、一个简单的小例子代码如下:@Servic
- 安装方式:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可。先说说DTODTO是个什么东东?DTO
- 1.下载jenkins 下载地址:https://jenkins.io/  
- Java 目前已经出到13的版本,但是国内大部分公司应该都停留在 Java 8 的版本(不敢承担升级带来的风险)。在Java8中给我们带来了
- C# 获取某个时间的0点0分和23点59分59秒,具体代码如下所示:C#获取当月第一天和最后一天当月第一天0时0分0秒:DateTime.N
- 此文主要想和大家分享的是这段时间,对权限管理和设计的断断续续的思考学习,和个人的一些软件开发等方面的看法。 提到'权限管理和设计
- 文章描述一般情况下,我们的日志文件是用来记录一些关键操作或者异常,并且是后台存储,并不对外开放的;但是也有些时候,特别是做一些小工具程序,需
- 一、 代码块的概念在探究对象初始化顺序之前,我们先通过代码来了解一下代码块的概念。class Test{ public stat
- 本文实例讲述了C#实现对二维数组排序的方法。分享给大家供大家参考。具体实现方法如下:/// <summary>/// A gen
- 在拼接绝对路径的网址时,经常需要从Request.Url中获取根网址(比如https://git.oschina.net),然后与相对路径一
- 附GitHub源码:WebViewExplore先看图:在WebView页面长按时会弹出一个复制框,但如果里面的item不是我们想要的或者想
- 发现问题:之前用springAOP做了个操作日志记录,这次在往其他类上使用的时候,service一直注入失败,找了网上好多内容,发现大家都有
- sql语句是写在对应的xml文件中首先要解决maven默认不加载xml文件的问题1.首先要写入相关配置文件在pom 导入下面内容
- 人机交互过程中,当我们需要机器给我们反馈不确定的数字结果时,就会需要用到随机数了,那么,在Java中,我们应当如何来生成并使用随机数呢?一、
- 最近在公司,项目不是很忙了,偶尔看见一个兄台在CSDN求助,帮忙要一个自定义的渐变色进度条,我当时看了一下进度条,感觉挺漂亮的,就尝试的去自
- 1、右值1.1 简介首先区分一下左右值:左值是指存储在内存中、有明确存储地址(可取地址)的数据;右值是指可以提供数据值的数据(不可取地址)如
- 1、定义常量(1)const修饰变量,以下两种定义形式在本质上是一样的。它的含义是:const修饰的类型为TYPE的变量value是不可变的
- 一、新建短信微服务1、在service模块下创建子模块service-msm2.创建controller和service代码3.配置appl