【问题标题】:How to throw the last exception from Polly after the final retry of HttpClient's SendAsyncHttpClient的SendAsync最终重试后如何从Polly抛出最后一个异常
【发布时间】:2020-06-24 22:07:00
【问题描述】:

要求:Polly 在使用HttpClientSendAsync 方法时,应在最终重试失败后抛出实际异常(来自下游系统)。

目前,我在最终重试后总是得到TaskCancelledException,我希望在最终重试失败后从下游端点获得实际异常。

我的 HttpClient 注册:

AddPollyPolicies(services, configuration);
services.AddHttpClient<TClient, TImplementation>()
    .ConfigureHttpClient((sp, options) =>
    {
        var httpClientOptions = sp.GetRequiredService<IOptions<TClientOptions>>().Value;
        options.BaseAddress = new Uri(httpClientOptions.BaseAddress);
        // Overall timeout of http client including all polly retries
        options.Timeout =
            TimeSpan.FromMilliseconds(httpClientOptions.OverallHttpClientTimeoutInMilliSeconds);
    })
    .AddHttpMessageHandler<OutboundRequestTimingDelegatingHandler>()
    .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler())
    .AddHttpMessageHandler<CorrelationIdDelegatingHandler>()
    .AddPolicyHandlerFromRegistry(PolicyName.HttpRetry);

我的 PolicyRegistry 注册:

private static void AddPollyPolicies(IServiceCollection services, IConfiguration configuration)
{
    var section = configuration.GetSection(PoliciesConfigurationSectionName);
    services.Configure<PolicyOptions>(configuration);
    var policyOptions = section.Get<PolicyOptions>();

    var registry = new PolicyRegistry
    {
        {
            PolicyName.HttpRetry, RetryPolicyAsync(policyOptions.HttpRetry.MedianFirstRetryDelayInMilliSec,
                policyOptions.HttpRetry.RetryCount)
        }
    };

    services.AddPolicyRegistry(registry);
}

我的重试策略:

private static AsyncRetryPolicy<HttpResponseMessage> RetryPolicyAsync(int medianFirstRetryDelayInMilliSec, int retryCount)
{
    //Retry delay algorithm - DecorrelatedJitterBackoffV2 - https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry#wait-and-retry-with-jittered-back-off
    var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay:
        TimeSpan.FromMilliseconds(medianFirstRetryDelayInMilliSec), retryCount: retryCount);

    // Retry policy
    var waitAndRetryPolicy = Policy
        .Handle<HttpRequestException>()
        .OrResult<HttpResponseMessage>(r => HttpStatusCodesWorthRetrying.ContainsKey(r.StatusCode))
        .Or<TimeoutRejectedException>()
        .WaitAndRetryAsync(delay, (result, span, count, ctx) =>
            Console.WriteLine($"Retrying count is ({count})..."));


    return waitAndRetryPolicy;
}

提前致谢!

【问题讨论】:

  • 您的OverallHttpClientTimeoutInMilliSeconds 设置有多大?您的 HttpClient“全局”超时似乎缩短了您的弹性策略。

标签: c# .net asp.net-core .net-core polly


【解决方案1】:

您所描述的是 Polly 处理异常的默认方式,任何和所有最终失败都应该以这种方式表现。

请参阅文档,以及他们的unit tests

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2017-11-27
    • 1970-01-01
    • 2018-05-19
    相关资源
    最近更新 更多