如何在Polly中创建策略以支持http响应重试后标头

时间:2019-11-13 06:17:41

标签: c# polly

我正在尝试创建Polly策略来支持http response retry-after header

 var retryAfterPolicy = Policy
               .HandleResult<HttpResponseMessage>(r => r?.Headers?.RetryAfter != null)
               .WaitAndRetryAsync(retryCount: retryAttemptsBeforeBreaking,
                                    sleepDurationProvider: (count, response, context) => GetServerWaitDuration(response)
                );

上面的代码给我错误,

  

“ PolicyBuilder”不包含“ WaitAndRetryAsync”的定义,最佳扩展方法重载“ RetrySyntaxAsync.WaitAndRetryAsync(PolicyBuilder,int,Func)”要求接收者的类型为“ PolicyBuilder”

如何支持这一点,我还必须将其与其他政策(例如circuitBreakerPolicy)一起包装?

1 个答案:

答案 0 :(得分:2)

按如下所示更新您的代码,它应该可以工作

            var retryAfterPolicy = Policy
             .HandleResult<HttpResponseMessage>(r => r => r?.Headers?.RetryAfter != null)
             .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2), (result, timeSpan, retryCount, context) =>
                          {
                           _logger.LogCritical($"Request failed with {result.Result.StatusCode}. Waiting {timeSpan} before next retry. Retry attempt {retryCount}");
                          });