封装处理下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(2, (ex, count) => { _logger.LogError("执行失败!重试次数 {0} 异常来自 {1}", count, ex.GetType().Name); }); policy.Execute(action); }
调用重试
_pollyHelper.PollyRetry<UserServicesDomainException>(() => { throw new UserServicesDomainException("斯大林附近打开了房间"); });
执行结果如下