【发布时间】:2020-06-24 22:07:00
【问题描述】:
要求:Polly 在使用HttpClient 的SendAsync 方法时,应在最终重试失败后抛出实际异常(来自下游系统)。
目前,我在最终重试后总是得到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