gpt4 book ai didi

c# - 一种为 http 响应编写重试的优雅方法

转载 作者:行者123 更新时间:2023-12-05 09:15:17 25 4
gpt4 key购买 nike

有没有一种优雅的方式来做到这一点?我在特定时间传递了太多请求,引发了 503(服务不可用)异常。谢谢

    protected void CallApi(string uriString)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync(uriString, new StringContent("{ Data to be posted }")).Result;

for (int i = 0; i < MaxRetries; i++)
{
if (response.IsSuccessStatusCode)
{
break;
}
else
{
Thread.Sleep(TimeSpan.FromMinutes(1));
response = client.PostAsync(uriString, new StringContent("{ Data to be posted }")).Result;
}
}
throw new Exception("status : " + (int)response.StatusCode + ", Content :" + response.Content.ReadAsStringAsync().Result);
}
}

最佳答案

Polly 示例:

var httpClient = new HttpClient();
var maxRetryAttempts = 3;
var pauseBetweenFailures = TimeSpan.FromSeconds(2);

var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures);

await retryPolicy.ExecuteAsync(async () =>
{
var response = await httpClient
.DeleteAsync("https://example.com/api/products/1");
response.EnsureSuccessStatusCode();
});

关于c# - 一种为 http 响应编写重试的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52808500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com