返回顶部

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; }
    }

 

posted @ 2022-07-07 23:39  SportSky  阅读(151)  评论(0编辑  收藏  举报
作者:SportSky 出处: http://www.cnblogs.com/sportsky/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。