有时候我们需要调用其他API的时候出现暂时连接不通超时的情况,那这时候可以通过Polly进行Retry。
1、从nuget引用polly,
2、定义需要处理的异常有哪些,比如
Policy.Handle<TimeoutException>().Or<FormatException>()
3、异常发生时候需要定义重试几次,等多久后再重试,比如
var policy = Policy.Handle<TimeoutException>().RetryAsync(3, (exception, retryCount) =>
{
});
4、代码跟policy结合起来的demo如下:
private static Logger logger = LogManager.GetCurrentClassLogger(); private static void Main(string[] args) { var policy = Policy.Handle<TimeoutException>() .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(5), (exception, retryCount) => { logger.Error(exception); }); var result = policy.ExecuteAsync(() => Test()); } private static async Task Test() { using (var httpClient = new HttpClient()) { var response = httpClient.GetAsync("http://news.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result; await response.Content.ReadAsStringAsync(); } }
时间: 2024-11-10 01:24:20