Pathoschild/FluentHttpClient 使用 Polly 进行自定义重试协调时出错

Pathoschild/FluentHttpClient giving error for custom retry coordination using Polly

我指的是这个 https://github.com/Pathoschild/FluentHttpClient#custom-retry--coordination 创建自定义重试协调并尝试在此处使用 Polly,但出现以下错误,

'PolicyBuilder< HttpResponseMessage>' does not contain a definition for 'Retry' and the best extension method overload 'RetrySyntax.Retry(PolicyBuilder, int, Action)' requires a receiver of type 'PolicyBuilder'

这里有什么问题吗?

public class PollyCoordinator : IRequestCoordinator
{
    public Task<HttpResponseMessage> ExecuteAsync(IRequest request, Func<IRequest, Task<HttpResponseMessage>> dispatcher)
    {
        int[] retryCodes = { 408, 500, 502, 503, 504 };
        return Policy
            .HandleResult<HttpResponseMessage>(r => retryCodes.Contains((int)r.StatusCode))
            .Retry(3, async () => await dispatcher(request));
    }
}

我更新了the example in the FluentHttpClient readme。这是您的代码的固定版本:

public class PollyCoordinator : IRequestCoordinator
{
    public Task<HttpResponseMessage> ExecuteAsync(IRequest request, Func<IRequest, Task<HttpResponseMessage>> send)
    {
        int[] retryCodes = { 408, 500, 502, 503, 504 };
        return Policy
            .HandleResult<HttpResponseMessage>(r => retryCodes.Contains((int)r.StatusCode)) // should we retry?
            .RetryAsync(3) // up to 3 retries
            .ExecuteAsync(() => send(request)); // begin handling request
    }
}

如果您希望在每次重试之间有延迟(推荐),您可以将 RetryAsync(3) 替换为 WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(attempt)).