请求重试 Apache HttpClient 之间的超时 [英] Timeout between request retries Apache HttpClient

查看:51
本文介绍了请求重试 Apache HttpClient 之间的超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以分享如何配置现代 HttpClient 4.5.3 以重试失败的请求并在每次重试前等待一段时间吗?

Could somebody share how to configure modern HttpClient 4.5.3 to retry failed requests and wait for some time before each retry?

到目前为止,我认为 .setRetryHandler(new DefaultHttpRequestRetryHandler(X, false)) 将允许重试请求 X 次.

So far it looks like I got it correctly that .setRetryHandler(new DefaultHttpRequestRetryHandler(X, false)) will allow to retry requests X times.

但我无法理解如何配置退避:.setConnectionBackoffStrategy()/.setBackoffManager() 根据 JavaDocs 规范其他内容,而不是重试之间的超时.

But I cannot understand how to configure backoff: .setConnectionBackoffStrategy() / .setBackoffManager() according to JavaDocs regulate something else, not timeout between retries.

推荐答案

关于动态延迟,我想这样建议:​​

About the dynamic delay, I want to suggest this:

CloseableHttpClient client = HttpClientBuilder.create()
    .setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return executionCount <= maxRetries ;
        }
    })
    .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
        int waitPeriod = 100;
        @Override
        public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
            waitPeriod *= 2;
            return executionCount <= maxRetries &&
               response.getStatusLine().getStatusCode() >= 500; //important!
        }

        @Override
        public long getRetryInterval() {
            return waitPeriod;
        }
    })
    .build();

附录:请注意,如果出现超时、端口未打开或连接关闭等 IO 错误,则不会调用 ServiceUnavailableRetryStrategy.retryRequest.在这种情况下,只会调用 HttpRequestRetryHandler.retryRequest ,并且重试将立即发生或在固定延迟后发生(我最终无法澄清这一点).所以oleg的答案实际上是正确的.在 HttpClient 4.5 的支持下无法做到这一点.

Appendix: Please note, that ServiceUnavailableRetryStrategy.retryRequest will NOT be called, if there was an IO error like timeout, port not open or connection closed. In such cases, only HttpRequestRetryHandler.retryRequest will be called, and the retry will happen either immediately or after a fixed delay (I could not finally clarify this). So oleg's answer is actually the right one. There is no way to do it with support of HttpClient 4.5.

(我实际上想称其为设计错误,因为在现代微服务环境中,IO 错误后的延迟重试至关重要.)

(I would actually like to call this a design bug, as delayed retries after an IO error are vitally important in a modern microservice environment.)

这篇关于请求重试 Apache HttpClient 之间的超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆