欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c# 如何更簡單的使用Polly

 更新時間:2021年03月23日 10:56:03   作者:victor.x.qu  
這篇文章主要介紹了c# 如何更簡單的使用Polly,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下

Polly是一個C#實現(xiàn)的彈性瞬時錯誤處理庫
它可以幫助我們做一些容錯模式處理,比如:

  • 超時與重試(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
 });

但是每個地方我們都得這樣寫,個人還是不喜,
那么怎么簡化呢?
當(dāng)然是使用 Norns.Urd 這些AOP框架封裝我們常用的東西做成 Attribute 啦

如何實現(xiàn)簡化呢?

我們來嘗試將 Retry功能 做成 RetryAttribute吧

1.安裝 AOP 框架

自己寫多累呀,用現(xiàn)成的多好呀

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++; // 每調(diào)用一次就加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); //我們期望調(diào)用總共 3 次
 }
 }

是的,就是這樣,我們可以在任何地方使用 RetryAttribute

當(dāng)然,一些常見的方法已經(jīng)封裝在了 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()

有關(guān) Norns.Urd, 大家可以查看 https://fs7744.github.io/Norns.Urd/zh-cn/index.html

以上就是c# 如何更簡單的使用Polly的詳細(xì)內(nèi)容,更多關(guān)于c# 使用Polly的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C#中Linq查詢基本操作使用實例

    C#中Linq查詢基本操作使用實例

    這篇文章主要介紹了C#中Linq查詢基本操作使用實例,有需要的朋友可以參考一下
    2013-12-12
  • C# 通過ServiceStack 操作Redis

    C# 通過ServiceStack 操作Redis

    這篇文章主要介紹了C# 通過ServiceStack 操作Redis的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-03-03
  • C# UDP網(wǎng)絡(luò)通信的實現(xiàn)示例

    C# UDP網(wǎng)絡(luò)通信的實現(xiàn)示例

    UDP協(xié)議是互聯(lián)網(wǎng)上使用最廣泛的傳輸協(xié)議之一,具有簡單、高效和不可靠的特點,本文主要介紹了C# UDP網(wǎng)絡(luò)通信的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2024-06-06
  • C#實現(xiàn)隨機數(shù)產(chǎn)生類實例

    C#實現(xiàn)隨機數(shù)產(chǎn)生類實例

    這篇文章主要介紹了C#實現(xiàn)隨機數(shù)產(chǎn)生類,實例分析了C#隨機數(shù)的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-03-03
  • 一步步教你如何創(chuàng)建第一個C#項目

    一步步教你如何創(chuàng)建第一個C#項目

    這篇文章主要給大家介紹了關(guān)于如何創(chuàng)建第一個C#項目的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-12-12
  • 解析C#中的分部類和分部方法

    解析C#中的分部類和分部方法

    這篇文章主要介紹了C#中的分部類和分部方法,講解了類的拆分和方法的定義的拆分,需要的朋友可以參考下
    2016-01-01
  • C++中#include頭文件的示例詳解

    C++中#include頭文件的示例詳解

    在C++中,所有的文件操作,都是以流(stream)的方式進行的,fstream也就是文件流file stream。這篇文章主要介紹了C++中#include頭文件,需要的朋友可以參考下
    2020-02-02
  • C# mysql 插入數(shù)據(jù),中文亂碼的解決方法

    C# mysql 插入數(shù)據(jù),中文亂碼的解決方法

    用C#操作mysql時, 插入數(shù)據(jù)中文都是亂碼,只顯示問號,數(shù)據(jù)庫本身使用的是utf-8字符
    2013-10-10
  • Unity2D實現(xiàn)游戲回旋鏢

    Unity2D實現(xiàn)游戲回旋鏢

    這篇文章主要為大家詳細(xì)介紹了Unity2D實現(xiàn)游戲回旋鏢,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • C#對XtraGrid控件實現(xiàn)主從表關(guān)系綁定

    C#對XtraGrid控件實現(xiàn)主從表關(guān)系綁定

    這篇文章介紹了C#對XtraGrid控件實現(xiàn)主從表關(guān)系綁定的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06

最新評論