Polly如何在c#项目中使用
今天就跟大家聊聊有关Polly如何在c#项目中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
Polly是一个C#实现的弹性瞬时错误处理库它可以帮助我们做一些容错模式处理,比如:
超时与重试(Timeout and Retry)
熔断器(Circuit Breaker)
舱壁隔离(Bulkhead Isolation)
回退(Fallback)
使用也是非常简单的,比如:
//Retrymultipletimes,callinganactiononeachretry //withthecurrentexceptionandretrycount Policy .Handle<SomeExceptionType>() .Retry(3,onRetry:(exception,retryCount)=> { //Addlogictobeexecutedbeforeeachretry,suchaslogging });
但是每个地方我们都得这样写,个人还是不喜,那么怎么简化呢?当然是使用 Norns.Urd 这些AOP框架封装我们常用的东西做成 Attribute 啦
如何实现简化呢?
我们来尝试将 Retry功能 做成 RetryAttribute吧
1.安装 AOP 框架
自己写多累呀,用现成的多好呀
dotnetaddpackageNorns.Urd
2.编写 Retry InterceptorAttribute
publicclassRetryAttribute:AbstractInterceptorAttribute { privatereadonlyintretryCount; publicRetryAttribute(intretryCount) { this.retryCount=retryCount; } publicoverrideasyncTaskInvokeAsync(AspectContextcontext,AsyncAspectDelegatenext) { awaitPolicy.Handle<Exception>() .RetryAsync(retryCount) .ExecuteAsync(()=>next(context)); } }
3.考虑到 async 和 sync 在Polly 有差异,那么我们兼容一下吧
publicclassRetryAttribute:AbstractInterceptorAttribute { privatereadonlyintretryCount; publicRetryAttribute(intretryCount) { this.retryCount=retryCount; } publicoverridevoidInvoke(AspectContextcontext,AspectDelegatenext) { Policy.Handle<Exception>() .Retry(retryCount) .Execute(()=>next(context)); } publicoverrideasyncTaskInvokeAsync(AspectContextcontext,AsyncAspectDelegatenext) { awaitPolicy.Handle<Exception>() .RetryAsync(retryCount) .ExecuteAsync(()=>next(context)); } }
4.我们来做个测试吧
publicclassRetryTest { publicclassDoRetryTest { publicintCount{get;set;} [Retry(2)]//使用Retry publicvirtualvoidDo() { if(Count<50) { Count++;//每调用一次就加1 thrownewFieldAccessException(); } } } publicDoRetryTestMock() { returnnewServiceCollection() .AddTransient<DoRetryTest>() .ConfigureAop() .BuildServiceProvider() .GetRequiredService<DoRetryTest>(); } [Fact] publicvoidRetryWhenSync() { varsut=Mock(); Assert.Throws<FieldAccessException>(()=>sut.Do()); Assert.Equal(3,sut.Count);//我们期望调用总共3次 } }
是的,就是这样,我们可以在任何地方使用 RetryAttribute
当然,一些常见的方法已经封装在了 Norns.Urd.Extensions.Polly
这里通过Norns.Urd将Polly的各种功能集成为更加方便使用的功能
如何启用 Norns.Urd + Polly, 只需使用EnablePolly()
如:
newServiceCollection() .AddTransient<DoTimeoutTest>() .ConfigureAop(i=>i.EnablePolly())
TimeoutAttribute
[Timeout(seconds:1)]//timeout1seconds,whentimeoutwillthrowTimeoutRejectedException doubleWait(doubleseconds); [Timeout(timeSpan:"00:00:00.100")]//timeout100milliseconds,onlyworkonasyncmethodwhennoCancellationToken asyncTask<double>WaitAsync(doubleseconds,CancellationTokencancellationToken=default); [Timeout(timeSpan:"00:00:01")]//timeout1seconds,butnoworkonasyncmethodwhennoCancellationToken asyncTask<double>NoCancellationTokenWaitAsync(doubleseconds);
RetryAttribute
[Retry(retryCount:2,ExceptionType=typeof(AccessViolationException))]//retry2timeswhenifthrowException voidDo()
CircuitBreakerAttribute
[CircuitBreaker(exceptionsAllowedBeforeBreaking:3,durationOfBreak:"00:00:01")] //or [AdvancedCircuitBreaker(failureThreshold:0.1,samplingDuration:"00:00:01",minimumThroughput:3,durationOfBreak:"00:00:01")] voidDo()
BulkheadAttribute
[Bulkhead(maxParallelization:5,maxQueuingActions:10)] voidDo()
看完上述内容,你们对Polly如何在c#项目中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注恰卡编程网行业资讯频道,感谢大家的支持。
推荐阅读
-
Web应用从零开始,初学者友好型开发教程
-
容器化最佳实践:Docker 与 Kubernetes 在微服务架构中的协同设计
-
AWS Cloud9 使用攻略:云端 IDE 如何无缝集成 Lambda 与 S3 服务?
-
Heroku vs AWS Elastic Beanstalk:快速部署 Web 应用的平台对比
-
Kubernetes 集群部署避坑:资源调度、服务发现与滚动更新策略
-
Docker 镜像优化指南:分层构建、瘦身技巧与多阶段编译实践
-
Postman 接口测试全流程:从 API 设计到自动化测试脚本编写
-
pytest 框架进阶:自定义 fixture、插件开发与持续集成集成方案
-
JUnit 5 新特性:参数化测试、扩展模型与微服务测试实践
-
Chrome DevTools 性能分析:FPS 监控、内存快照与网络请求优化指南