首页 > 数据库 > 数据库开发技术 > 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;
//}
//
}
}
}
原文作者:后端Q;如有侵权,请联系管理员删除。