Polly服务治理(简单使用)
NuGet:Polly
一、服务治理说明
1、重试(Retry)
2、断路器(熔断)(Circuit-Breaker)
3、超时检测(TimeOut)
4、缓存(Cache)
5、降级(Fallback)
二、简单使用
static async Task Main(string[] args) { var option = new ResilientHttpClientConfigOption() { TimeoutMillseconds = 1000 * 120, RetryCount = 3, DurationSecondsOfBreak = 15, ExceptionsAllowedBeforeBreaking = 3 }; var policy = new IAsyncPolicy[] { Policy.TimeoutAsync(TimeSpan.FromMilliseconds(option.TimeoutMillseconds), Polly.Timeout.TimeoutStrategy.Pessimistic), Policy.Handle<Exception>() .WaitAndRetryAsync( // 重试次数 option.RetryCount, // 指数退避算法 retryAttempt => TimeSpan.FromMilliseconds(Math.Pow(2, retryAttempt)), // 重试是执行的方法 (exception, timeSpan, retryCount, context) => { var msg = $"Retry {retryCount} implemented with Polly's RetryPolicy " + $"of {context.PolicyKey} " + $"at {context.OperationKey}, " + $"due to: {exception}."; Console.WriteLine(msg); }), Policy.Handle<Exception>() .CircuitBreakerAsync( // 异常阀值,超过时熔断 option.ExceptionsAllowedBeforeBreaking, //熔断后,需要等待多久不想回复 TimeSpan.FromSeconds(option.DurationSecondsOfBreak), (exception, duration) => { Console.WriteLine("Circuit breaker opened"); }, () => { //熔断已经关闭 Console.WriteLine("Circuit breaker reset"); }) }; var policyWrap= Policy.WrapAsync(policy.ToArray()); var result= await policyWrap.ExecuteAsync(() => { // do something // 此处可以进行http请求 return PolicyTest(); }); Console.WriteLine("Hello World!"); }
public static async Task<string> PolicyTest() { throw new Exception("请求异常"); }
public class ResilientHttpClientConfigOption { /// <summary> /// 超时时间(毫秒) /// </summary> public int TimeoutMillseconds { get; set; } /// <summary> /// 重试次数 /// </summary> public int RetryCount { get; set; } /// <summary> /// 最大允许的异常次数,超过则自动熔断 /// </summary> public int ExceptionsAllowedBeforeBreaking { get; set; } /// <summary> /// 熔断持续的秒数 /// </summary> public int DurationSecondsOfBreak { get; set; } }