已被.NET基金会承认的弹性和瞬态故障处理库Polly介绍

前言

本节咱们来介绍一款强大的库Polly,Polly是一种.NET弹性和瞬态故障处理库,容许咱们以很是顺畅和线程安全的方式来执诸如行重试,断路,超时,故障恢复等策略。 Polly针对对.NET 4.0,.NET 4.5和.NET Standard 1.1以及.NET Core实现,该项目做者现已成为.NET基金会一员,项目一直在不停迭代和更新,项目地址【https://github.com/App-vNext/Polly】,你值得拥有。接下来咱们以.NET Framework  4.5来演示它的强大功能。git

Introduce Polly

首先咱们得下载Polly包,最新版本为5.3.1,以下:github

该库实现了七种恢复策略,下面我一一为您来介绍。数据库

重试策略(Retry)

重试策略针对的前置条件是短暂的故障延迟且在短暂的延迟以后可以自我纠正。容许咱们作的是可以自动配置重试机制。缓存

断路器(Circuit-breaker)

断路器策略针对的前置条件是当系统繁忙时,快速响应失败总比让用户一直等待更好。保护系统故障免受过载,Polly能够帮其恢复。安全

超时(Timeout)

超时策略针对的前置条件是超过必定的等待时间,想要获得成功的结果是不可能的,保证调用者没必要等待超时。微信

隔板隔离(Bulkhead Isolation)

隔板隔离针对的前置条件是当进程出现故障时,多个失败一直在主机中对资源(例如线程/ CPU)一直占用。下游系统故障也可能致使上游失败。这两个风险都将形成严重的后果。都说一粒老鼠子屎搅浑一锅粥,而Polly则将受管制的操做限制在固定的资源池中,免其余资源受其影响。网络

缓存(Cache)

缓存策略针对的前置条件是数据不会很频繁的进行更新,为了不系统过载,首次加载数据时将响应数据进行缓存,若是缓存中存在则直接从缓存中读取。框架

回退(Fallback)

操做仍然会失败,也就是说当发生这样的事情时咱们打算作什么。也就是说定义失败返回操做。async

策略包装(PolicyWrap)

策略包装针对的前置条件是不一样的故障须要不一样的策略,也就意味着弹性灵活使用组合。ide

几种策略使用

一旦从事IT就得警戒异常并友好拥抱异常而非漠不关心,这个时候咱们利用try{}catch{}来处理。

            try
            {
                var a = 0;
                var b = 1 / a;
            }
            catch (DivideByZeroException ex)
            {

                throw ex;
            }

若咱们想重试三次,此时咱们只能进行循环三次操做。咱们只能简单进行处理,自从有了Polly,什么重试机制,超时都不在话下,下面咱们来简短介绍各类策略。Polly默认处理策略须要指定抛出的具体异常或者执行抛出异常返回的结果。处理单个类型异常以下:

Policy
  .Handle<DivideByZeroException>()

上述异常指尝试除以0,下面咱们演示下具体使用,咱们尝试除以0并用Polly指定该异常并重试三次。

        static int Compute()
        {
            var a = 0;
            return 1 / a;
        }
            try
            {
                var retryTwoTimesPolicy =
                     Policy
                         .Handle<DivideByZeroException>()
                         .Retry(3, (ex, count) =>
                         {
                             Console.WriteLine("执行失败! 重试次数 {0}", count);
                             Console.WriteLine("异常来自 {0}", ex.GetType().Name);
                         });
                retryTwoTimesPolicy.Execute(() =>
                {
                    Compute();
                });
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine($"Excuted Failed,Message: ({e.Message})");

            }

若是咱们想指定处理多个异常类型经过OR便可。

Policy
  .Handle<DivideByZeroException>()
  .Or<ArgumentException>()

固然还有更增强大的功能,好比在微信支付时,微信回调咱们的应用程序时,此时若失败,想必微信那边也会作重试机制,例如隔一段时间重试调用一次,重复调用几回后仍失败则再也不回调。咱们利用Polly则能够演示等待重试机制。

        /// <summary>
        /// 抛出异常
        /// </summary>
        static void ZeroExcepcion()
        {
            throw new DivideByZeroException();
        }
        /// <summary>
        /// 异常信息
        /// </summary>
        /// <param name="e"></param>
        /// <param name="tiempo"></param>
        /// <param name="intento"></param>
        /// <param name="contexto"></param>
        static void ReportaError(Exception e, TimeSpan tiempo, int intento, Context contexto)
        {
            Console.WriteLine($"异常: {intento:00} (调用秒数: {tiempo.Seconds} 秒)\t执行时间: {DateTime.Now}");
        }
            try
            {
                var politicaWaitAndRetry = Policy
                    .Handle<DivideByZeroException>()
                    .WaitAndRetry(new[]
                    {
                        TimeSpan.FromSeconds(1),
                        TimeSpan.FromSeconds(3),
                        TimeSpan.FromSeconds(5),
                        TimeSpan.FromSeconds(7)
                    }, ReportaError);
                politicaWaitAndRetry.Execute(() =>
                {
                    ZeroExcepcion();
                });
            }
            catch (Exception e)
            {
                Console.WriteLine($"Executed Failed,Message:({e.Message})");
            }

咱们讲完默认策略和重试策略,再来看看反馈策略,翻译的更通俗一点则是执行失败后返回的结果,此时要为Polly指定返回类型,而后指定异常,最后调用Fallback方法。

        static string ThrowException()
        {
            throw new Exception();
        }
           var fallBackPolicy =
                Policy<string>
                    .Handle<Exception>()
                    .Fallback("执行失败,返回Fallback");

            var fallBack = fallBackPolicy.Execute(() =>
            {
                return ThrowException();
            });
            Console.WriteLine(fallBack);

包裹策略说到底就是混合多种策略,并执行。

          var fallBackPolicy =
                Policy<string>
                    .Handle<Exception>()
                    .Fallback("执行失败,返回Fallback");

            var fallBack = fallBackPolicy.Execute(() =>
            {
                return ThrowException();
            });
            Console.WriteLine(fallBack);

            var politicaWaitAndRetry = 
                Policy<string>
                    .Handle<Exception>()
                    .Retry(3, (ex, count) =>
                    {
                        Console.WriteLine("执行失败! 重试次数 {0}", count);
                        Console.WriteLine("异常来自 {0}", ex.GetType().Name);
                    });

            var mixedPolicy = Policy.Wrap(fallBackPolicy, politicaWaitAndRetry);
            var mixedResult = mixedPolicy.Execute(ThrowException);
            Console.WriteLine($"执行结果: {mixedResult}");

至此关于Polly的基本介绍就已结束,该库仍是很是强大,更多特性请参考上述github例子,接下来咱们来看看两种具体场景。

ASP.NET Web APi使用Polly重试机制

在Polly v4.30中以上能够利用HandleResult指定返回结果,以下:

Policy
  .HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.NotFound)

基于此咱们彻底能够利用执行Web APi中的响应策略,以下:

 public readonly RetryPolicy<HttpResponseMessage> _httpRequestPolicy;

拿到响应中状态码,若为500则重试三次。

 _httpRequestPolicy = Policy.HandleResult<HttpResponseMessage>(
            r => r.StatusCode == HttpStatusCode.InternalServerError)
            .WaitAndRetryAsync(3,
            retryAttempt => TimeSpan.FromSeconds(retryAttempt));

上述获取请求响应策略在构造函数中获取。

    public class PollyController : ApiController
    {
        public readonly RetryPolicy<HttpResponseMessage> _httpRequestPolicy;
        public PollyController()
        {
            _httpRequestPolicy = Policy.HandleResult<HttpResponseMessage>(
            r => r.StatusCode == HttpStatusCode.InternalServerError)
            .WaitAndRetryAsync(3,
            retryAttempt => TimeSpan.FromSeconds(retryAttempt));
        }
    }

此时调用接口时执行策略的Execute或者ExecuteAsync方法便可。

        public async Task<IHttpActionResult> Get()
        {
            var httpClient = new HttpClient();
            string requestEndpoint = "http://localhost:4096";

            HttpResponseMessage httpResponse = await _httpRequestPolicy.ExecuteAsync(() => httpClient.GetAsync(requestEndpoint));

            IEnumerable<string> numbers = await httpResponse.Content.ReadAsAsync<IEnumerable<string>>();

            return Ok(numbers);
        }

你觉得仅限于在Web APi中使用吗?在其余框架中也可使用,例如EntityFramework 6.x中,在EntityFramework 6+上出现了执行策略,也就是执行重试机制,这个时候咱们依然能够借助Polly轮子来实现。

EntityFramework 6.x使用Polly重试机制

在EntityFramework 6.x中有以下执行策略接口,看起来是否是和Polly中的Execute方法是否是很相似。

    //
    // 摘要:
    //     A strategy that is used to execute a command or query against the database, possibly
    //     with logic to retry when a failure occurs.
    public interface IDbExecutionStrategy
    {
        //
        // 摘要:
        //     Indicates whether this System.Data.Entity.Infrastructure.IDbExecutionStrategy
        //     might retry the execution after a failure.
        bool RetriesOnFailure { get; }

        //
        // 摘要:
        //     Executes the specified operation.
        //
        // 参数:
        //   operation:
        //     A delegate representing an executable operation that doesn't return any results.
        void Execute(Action operation);
        //
        // 摘要:
        //     Executes the specified operation and returns the result.
        //
        // 参数:
        //   operation:
        //     A delegate representing an executable operation that returns the result of type
        //     TResult.
        //
        // 类型参数:
        //   TResult:
        //     The return type of operation.
        //
        // 返回结果:
        //     The result from the operation.
        TResult Execute<TResult>(Func<TResult> operation);
        //
        // 摘要:
        //     Executes the specified asynchronous operation.
        //
        // 参数:
        //   operation:
        //     A function that returns a started task.
        //
        //   cancellationToken:
        //     A cancellation token used to cancel the retry operation, but not operations that
        //     are already in flight or that already completed successfully.
        //
        // 返回结果:
        //     A task that will run to completion if the original task completes successfully
        //     (either the first time or after retrying transient failures). If the task fails
        //     with a non-transient error or the retry limit is reached, the returned task will
        //     become faulted and the exception must be observed.
        Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken);
        //
        // 摘要:
        //     Executes the specified asynchronous operation and returns the result.
        //
        // 参数:
        //   operation:
        //     A function that returns a started task of type TResult.
        //
        //   cancellationToken:
        //     A cancellation token used to cancel the retry operation, but not operations that
        //     are already in flight or that already completed successfully.
        //
        // 类型参数:
        //   TResult:
        //     The result type of the System.Threading.Tasks.Task`1 returned by operation.
        //
        // 返回结果:
        //     A task that will run to completion if the original task completes successfully
        //     (either the first time or after retrying transient failures). If the task fails
        //     with a non-transient error or the retry limit is reached, the returned task will
        //     become faulted and the exception must be observed.
        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken);
    }

EntityFramework 6.x中的执行策略说到底就是数据库链接问题即弹性链接,若考虑到数据库过渡负载问题,此时应用程序和数据库之间存在网络问题的话。可能数据库链接在几秒内才返回,此时也没有什么很大的问题,咱们彻底能够再尝试一次,此时或许过了链接频繁期,保证链接立马恢复。若是数据库链接一会恢复不了呢?或许是五分钟,又或者是半个小时。若是咱们只是一味盲目的进行重试,这显然不可取。若是咱们的应用程序链接超时时间超过了20秒,若咱们选择继续链接到数据库,咱们将很快用完咱们应用程序池中的工做线程。一直等待数据库的响应。此时网站将彻底无响应,同时会给用户页面无响应的友好提醒。这是Polly库中描述断路器的很好例子,换句话说若是咱们捕获了m个数量的SqlExceptions,假设数据库有其余问题存在,致使咱们不能在n秒内再尝试链接数据库。此时在数据库链接上存在一个问题,那就是阻塞了咱们的应用程序工做线程被挂起,咱们试图链接数据库,咱们假设不可用的话,可是咱们要打破这种不可用,那就用Polly吧。

 

咱们看到上述EntityFramework 6.x实现了IDbExecutionStrategy接口,但没有实现如Polly中的断路器模式,EntityFramework 6.x中的执行策略只是重试机制而已。 好比SqlAzureExecutionStrategy将在指定的时间段内重试指定的次数,直到一段时间段过去,重试指数事后,接着就是失败。 同时全部后续调用将执行相同操做,重试并失败。 这是调用数据库时最好的策略吗? 不敢确定,或许Polly中的断路器模式值得咱们借鉴。咱们本身来实现上述执行策略接口。

    public class CirtuitBreakerExecutionStrategy : IDbExecutionStrategy
    {
        private Policy _policy;

        public CirtuitBreakerExecutionStrategy(Policy policy)
        {
            _policy = policy;
        }

        public void Execute(Action operation)
        {

            _policy.Execute(() =>
            {
                operation.Invoke();
            });
        }

        public TResult Execute<TResult>(Func<TResult> operation)
        {
            return _policy.Execute(() =>
            {
                return operation.Invoke();
            });
        }

        public async Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken)
        {
            await _policy.ExecuteAsync(() =>
            {
                return operation.Invoke();
            });
        }

        public async Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken)
        {
            return await _policy.ExecuteAsync(() =>
            {
                return operation.Invoke();
            });
        }

        public bool RetriesOnFailure { get { return true; } }
    }

接下来在基于代码配置文件中设置咱们上述自定义实现的断路器模式。

    public class EFConfiguration : DbConfiguration
    {
        public Policy _policy;
        public EFConfiguration()
        {
            _policy = Policy.Handle<Exception>().CircuitBreaker(3, TimeSpan.FromSeconds(60));

            SetExecutionStrategy("System.Data.SqlClient", () => new CirtuitBreakerExecutionStrategy(_policy));
        }
    }

上述自定义实现执行策略不保证必定有用或许也是一种解决方案呢。

总结

本节咱们介绍了强大的Polly库和其对应使用的两种实际场景,有此轮子咱们何不用起,将其进行封装能够用于一切重试、缓存、异常等处理。 

个人博客即将入驻“云栖社区”,诚邀技术同仁一同入驻。
相关文章
相关标签/搜索