有時候我們需要調用其他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(); } }