为HTTP响应编写重试的一种优雅方式

时间:2018-10-15 01:04:43

标签: c# asp.net

有一种优雅的方法吗?我在特定时间内传递了太多请求,并抛出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);
        }
    }

1 个答案:

答案 0 :(得分:1)

多示例:

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();
});