在500响应之后,在进程重新启动之前不会再次发送请求



我正在使用Polly来实现请求重试。然而,在为请求返回500响应后,Polly不仅在重试时不发送请求,而且在重新启动进程之前根本不发送请求。相反,波利只是等待,直到超时。以下是代码:

var timeoutPolicy = TimeoutPolicy
.TimeoutAsync<HttpResponseMessage>(c => c.GetTimeout() ?? TimeSpan.FromSeconds(30)); //timeout para cada intento
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>() //tirado por la TimeoutPolicy
.WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) });
var policyHandler = new PolicyHandler(Policy.WrapAsync(retryPolicy, timeoutPolicy));

我如何修复代码,使Polly在500后重试时实际发送请求,以及以下请求?

我相信应用程序崩溃与这些策略无关。

我用一些调试日志修改了你的代码,如下所示:

public static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
var sw = Stopwatch.StartNew();
Console.WriteLine($"{sw.Elapsed.Seconds}: Application starts");
var timeoutPolicy = TimeoutPolicy
.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(30),
onTimeoutAsync: (ctx, ts, t) => {
Console.WriteLine($"{sw.Elapsed.Seconds}: Timeout has occurred");
return Task.CompletedTask;
});
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>() 
.WaitAndRetryAsync(
new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) },
onRetryAsync: (dr, ts) => {
Console.WriteLine($"{sw.Elapsed.Seconds}: Retry will be triggered");
return Task.CompletedTask;
});
var strategy = Policy.WrapAsync(retryPolicy, timeoutPolicy);
await strategy.ExecuteAsync(async (ct) => {
var response = await client.GetAsync("https://httpstat.us/500");
Console.WriteLine($"{sw.Elapsed.Seconds}: Response has been received");
return response;
}, CancellationToken.None);
Console.WriteLine($"{sw.Elapsed.Seconds}: Application finishes");
}
  • 每当httpClient收到响应时,它就会打印Response has been received
    • 我使用httpstat.us仅用于测试目的
  • 只要httpClient在30秒内没有收到响应,它就会打印Timeout has occurred
  • 每当应该触发重试策略但在延迟惩罚之前,它都会打印Retry will be triggered
  • 每当发出所有重试但均未成功或其中一个请求成功时,它都会打印Application finishes

在当前设置下,输出如下所示:

1: Response has been received
1: Retry will be triggered
2: Response has been received
2: Retry will be triggered
8: Response has been received
8: Retry will be triggered
18: Response has been received
18: Application finishes

正如您所看到的,我们已经发出了4个请求(一个初始请求和3次重试(,但没有成功。但最终,该应用程序仍在继续工作。

错误是由以下问题引起的

我就是这样修复的:

var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>() //tirado por la TimeoutPolicy
.WaitAndRetryAsync(new[] 
{ 
TimeSpan.FromSeconds(1), 
TimeSpan.FromSeconds(5), 
TimeSpan.FromSeconds(10) 
}, 
onRetry: (x, _) =>
{
//dispose response when retrying
x.Result?.Dispose();
});

相关内容

  • 没有找到相关文章

最新更新