Retry库

  一个重试库,支持线性和指数函数。。

  1.定义异常

 public class HttpExceptionPolicy

{

#region Constructors
public HttpExceptionPolicy()
{

}
#endregion

#region Exception Method
public bool ShouldRetryException(Exception ex) =>
IsRetriableException(ex);

protected bool IsRetriableException(Exception ex)
{
switch (ex)
{
case HttpRequestException httpRequestException when IsOK(httpRequestException.StatusCode):
return false;
case HttpRequestException httpRequestException when IsError(httpRequestException.StatusCode):
return false;
default:
return true;
};
}
#endregion

#region StatusCode Method
private static bool IsOK(HttpStatusCode? statusCode)
{
return (statusCode is not null ) && (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Unauthorized);
}


private static bool IsError(HttpStatusCode? statusCode)
{
return (statusCode is not null) &&
(statusCode == HttpStatusCode.BadRequest ||
statusCode == HttpStatusCode.NotFound);
}

#endregion
}

  2.定义指数RetryPolicy

HttpExceptionPolicy httpExceptionPolicy = new();

RetryPolicy retryPolicy = new(maxRetryAttempts: 3, baseDelay: 1.1, baseJitter: 0.05d, logger: logger);

var result = await retryPolicy.ExecuteWithExponentialAsync<string>(async (token) =>
{
using (HttpClient clinet = new HttpClient())
{
var result = await clinet.GetStringAsync("http://111/");
return result.Substring(0, 50);
}

}, httpExceptionPolicy.ShouldRetryException, _cancellationTokenSource.Token);

 

 3.线性RetryPolicy

 var logger = _loggerFactory.CreateLogger("HttpLinearRetrier");

HttpExceptionPolicy httpExceptionPolicy = new();

RetryPolicy retryPolicy = new(maxRetryAttempts: 10, baseDelay: 1, baseJitter: 0.05d, logger: logger);

var result = await retryPolicy.ExecuteWithFixeAsync<string>(async (token) =>
{
 using (HttpClient clinet = new HttpClient())
 {
  var result = await clinet.GetStringAsync("http://111/");
  return result.Substring(0, 50);
 }

}, httpExceptionPolicy.ShouldRetryException, _cancellationTokenSource.Token);

  

 

posted @ 2022-04-27 19:08  二杆  阅读(72)  评论(0)    收藏  举报