Polly公共处理 -重试(Retry)

时间:2023-03-09 07:33:43
Polly公共处理 -重试(Retry)

封装处理下Polly重试

private ILogger<PollyHelper> _logger;
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
public PollyHelper(ILogger<PollyHelper> logger)
{
_logger = logger;
}
/// <summary>
///
/// </summary>
/// <param name="exception"></param>
/// <param name="action"></param>
public void PollyRetry<T>(Action action) where T : Exception
{
var policy = Policy
.Handle<T>()
.Retry(, (ex, count) =>
{
_logger.LogError("执行失败!重试次数 {0}\r\n异常来自 {1}", count, ex.GetType().Name);
}); policy.Execute(action);
}

调用重试

 _pollyHelper.PollyRetry<UserServicesDomainException>(() =>
{
throw new UserServicesDomainException("斯大林附近打开了房间");
});

执行结果如下

Polly公共处理 -重试(Retry)