c# 弹性和瞬态故障处理库Polly

关于polly

polly文档中对自己介绍的原文是:

Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry,

Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.

从这段话我们可以知道polly项目是一个基于.NET开发的用来处理瞬故障的库,我们可以借助这个库以线程安全的形式实现

重试、断路、超时、隔离和回退策略.

polly的使用

在Nuget中下载Polly安装包,安装成功即可使用

Install-Package Polly

异常重试是最常使用的一个策略,其功能是当我们执行的方法体发生异常时,可以按照我们指定的次数进行重试

1、指定需要处理的异常

可以指定捕获执行的任务的异常类型,若执行任务的异常类型满足指定异常,那么重试机制将会生效

var policy = Policy.Handle<Exception>()

2、指定重试次数和监控重试

指定整个执行过程中需要重试多少次,且可以监控每次的重试信息,比如重试次数  异常以及重试的上下文信息

.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(2), (exception, retryCount) =>

3、指定执行的任务

指定执行的任务是整个异常重试的核心和监控对象,Execute支持多种重载.。

var result =   policy.ExecuteAsync(() => Test());
class Program
    {
      
        private static void Main(string[] args)
        {
            //var policy = Policy.Handle<Exception>()
            //    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(2), (exception, retryCount) =>
            //    {
            //        NLogger.Error(exception.ToString()+"------"+ $"第{retryCount}次重试");

            //    });


            var policy = Policy
              .Handle<Exception>()
              .RetryAsync(2, async (exception, retryCount) =>
              {
                  Console.WriteLine("333333:" + exception.Message + "------" + $"第{retryCount}次重试");
              });


            var result =   policy.ExecuteAsync(() => Test());
            //string r = result.ToString();
            Console.WriteLine("444444:");
            Console.ReadKey();
        }

        private static async Task Test()
        {
            //try
            //{

           
            Convert.ToInt32("w");
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync("http://news.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
                var  s=   await response.Content.ReadAsStringAsync();
                Console.WriteLine("111111:"+s);
            }
            //    return "url";
            //}
            //catch (Exception ex)
            //{
            //    throw new Exception();
            //    Console.WriteLine("222222:" + ex.Message);
            //    return null;
            //}
            
          // 
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值