我尝试使用Microsoft.Extensions.Http.Polly
策略处理器在TaskCanceledException
或http瞬时错误时重试,但它无法正常工作。
我写了下面这个最小的API只是为了测试:
Program.cs
using Polly;
using Polly.Extensions.Http;
using Polly.Retry;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
AsyncRetryPolicy<HttpResponseMessage>? policy = HttpPolicyExtensions.HandleTransientHttpError()
.Or<TaskCanceledException>()
.WaitAndRetryAsync(5, _ => TimeSpan.FromSeconds(5));
builder.Services.AddHttpClient("test", client =>
{
client.BaseAddress = new Uri("http://localhost:5000");
client.Timeout = TimeSpan.FromSeconds(2);
})
.AddPolicyHandler(policy);
WebApplication app = builder.Build();
app.MapPost("/status/{code}",
async (string code, IHttpClientFactory httpClientFactory, CancellationToken cancellationToken) =>
{
HttpClient client = httpClientFactory.CreateClient("test");
HttpResponseMessage response = await client.GetAsync($"/status/{code}", cancellationToken);
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync(cancellationToken);
});
app.MapPost("/timeout/{timeout:int}",
async (int timeout, IHttpClientFactory httpClientFactory, CancellationToken cancellationToken) =>
{
HttpClient client = httpClientFactory.CreateClient("test");
HttpResponseMessage response = await client.GetAsync($"/timeout/{timeout}", cancellationToken);
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync(cancellationToken);
});
#region Simulated API
app.MapGet("/status/{code:int}", (int code) => Results.StatusCode(code));
app.MapGet("/timeout/{timeout:int}", async (int timeout) =>
{
await Task.Delay(TimeSpan.FromSeconds(timeout));
return Results.Ok();
});
#endregion
app.Run();
在调用POST http://localhost:5000/timeout/10
之后,它会引发这个异常,而不会进行任何进一步的尝试:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 2 seconds elapsing.
---> System.TimeoutException: A task was canceled.
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Polly.Retry.AsyncRetryEngine.ImplementationAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Func`5 onRetryAsync, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider, Boolean continueOnCapturedContext)
at Polly.AsyncPolicy`1.ExecuteAsync(Func`3 action, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext)
at Microsoft.Extensions.Http.PolicyHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<>c__DisplayClass5_0.<<SendCoreAsync>g__Core|0>d.MoveNext()
--- End of stack trace from previous location ---
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Net.Http.HttpClient.HandleFailure(Exception e, Boolean telemetryStarted, HttpResponseMessage response, CancellationTokenSource cts, CancellationToken cancellationToken, CancellationTokenSource pendingRequestsCts)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Program.<>c.<<<Main>$>b__0_3>d.MoveNext() in Z:\Repositories\POCs\PollyRetryTest\PollyRetryTest\Program.cs:line 35
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Http.RequestDelegateFactory.<ExecuteTaskOfT>g__ExecuteAwaited|129_0[T](Task`1 task, HttpContext httpContext, JsonTypeInfo`1 jsonTypeInfo)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
我做错了什么?我必须覆盖主处理程序吗
1条答案
按热度按时间to94eoyn1#
TL;DR:HttpClient的超时作为每个逻辑请求的超时(覆盖所有重试尝试),而不是每个传输请求(覆盖单个尝试)。
让我们看看我们有什么在这里:
让我们看看会发生什么:
onRetry
/onRetryAsync
添加日志记录,则可以看到它仅触发一次GetAsync
调用抛出TCE,因为每个逻辑请求超时开始解决方案
使用超时策略定义每个传输请求的超时
timeout
将用作每个传输请求的超时(2秒)retry
支持超时策略(Or<TimeoutRejectedException>()
)timeout
和retry
策略结合在一起,以便进行协作您应该在日志中看到类似的内容:
让我们看看操作的顺序:
TimeoutRejectedException
RETRIED
TimeoutRejectedException
RETRIED
TimeoutRejectedException
RETRIED
HttpClient
投掷TaskCancelledException
注意事项
请注意,您可以使用Polly实现每个逻辑请求和每个传输请求的超时