我正在使用 httpClient 执行 POST 请求。我正在使用 Polly 进行重试。发生的情况是第一次尝试需要 14 秒,即使我指定了 2 秒的重试时间。第一次尝试在 14 秒后失败,然后有 2 秒的差距,直到第二次尝试。我希望它每 2 秒尝试一次并超时并重试任何错误。这是正确的做法吗?
var retryPolicy = Policy
.Handle<Exception>() // retry on any
.WaitAndRetryAsync(6,
retryAttempt => TimeSpan.FromMilliseconds(2000),
(response, calculatedWaitDuration, ctx) =>
{
Log.LogError($"Failed attempt {attempt++}. Waited for {calculatedWaitDuration}. Exception: {response?.ToString()}");
});
HttpResponseMessage httpResp = null;
await retryPolicy.ExecuteAsync(async () =>
{
httpResp = await DoPost();
httpResp?.EnsureSuccessStatusCode(); // throws HttpRequestException
return httpResp;
});
var respBody = await httpResp.Content.ReadAsStringAsync();
return respBody;
async Task<HttpResponseMessage> DoPost()
{
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(json, Encoding.UTF8, Constants.JsonContentType),
Headers = { Authorization = await GetAuthenticationTokenAsync() }
};
ServicePointManager.Expect100Continue = false;
var httpResponseMessage = await StaticHttpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
return httpResponseMessage;
}