• 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; }
        }
  • 相关阅读:
    java DMO及增删改查代码的自动生成
    如果有一天苹果免费了,支付宝怎么办
    jquery实现页面交互的几个小例子
    android中的所谓观察者模式
    随笔——runnable勘误以及其他
    android 源码角度全方位理解filter
    android 你的onfocuschangelistener和android:state_hovered为何不起作用
    android 如何阻断seekbar的触摸事件
    java 传值和传引用
    Android内存优化(使用SparseArray和ArrayMap代替HashMap)
  • 原文地址:https://www.cnblogs.com/sportsky/p/16444825.html
Copyright © 2020-2023  润新知