如何解决在 500 响应之后,在重新启动进程之前不会再次发送请求
我正在使用 Polly 来实现请求重试。但是,对于请求返回 500 响应后,Polly 不仅在重试时不发送请求,而且在重新启动进程之前根本不发送请求。相反,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 次重试以及后续请求时实际发送请求?
解决方法
错误是由以下issue
引起的这是我修复它的方式:
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();
});
,
我确实认为应用程序崩溃与这些政策无关。
我已经用一些调试日志修改了你的代码,如下所示:
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(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 次重试),但没有运气。但最终应用程序继续工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。