HttpClient和Polly延迟14秒

时间:2018-12-05 12:39:17

标签: httpclient polly

我正在使用httpClient进行POST请求。我正在使用Polly重试。发生的是,即使我指定了2s的重试时间,第一次尝试也需要14s。第一次尝试在14s后失败,然后有2s的间隔直到第二次尝试。我想要它每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;
            }

1 个答案:

答案 0 :(得分:1)

  

即使我指定了2s的重试时间,第一次尝试也需要14s。   第一次尝试在14s后失败,然后有2s的间隔直到第二次尝试。

是正确的。 WaitAndRetry是关于失败后要等待多久才能重试的specified in the documentation

  

我希望它每2秒尝试一次超时,然后重试任何错误。

要强制执行超时,请使用Polly的Timeout policy。要同时施加超时和重试,请使用Retry组合Timeout和PolicyWrap策略。因此,您可以像这样修改代码:

        var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(2000));

        var retryPolicy = Policy
            .Handle<Exception>()    // retry on any
            .WaitAndRetryAsync(6,  // or just RetryAsync() if you don't want any wait before retrying
                retryAttempt => /* a timespan, _if you want a wait before retrying */, 
                (response, calculatedWaitDuration, ctx) =>
                {
                    Log.LogError($"Failed attempt {attempt++}. Waited for {calculatedWaitDuration}. Exception: {response?.ToString()}");
                });

        var combinedPolicy = retryPolicy.WrapAsync(timeoutPolicy);

        HttpResponseMessage httpResp = null;
        await combinedPolicy.ExecuteAsync(async () =>
        {
            httpResp = await DoPost();
            httpResp?.EnsureSuccessStatusCode(); // throws HttpRequestException
            return httpResp;
        });

有关更多讨论和示例,请参见this similar stackoverflow question