ExponentialBackOffSchedulingStrategy
适用于缓存条目,这就是为什么它只能与CachingClient
。我认为它不能用于对失败的请求实施指数退避重试机制。
我将按照以下方式实施一个简单的指数退避策略:
class MyExponentialBackoffRetryHandler extends HttpRequestRetryHandler {
public MyExponentialBackoffRetryHandler(int maxNumRetries, int backOffRate, int initialExpiry, int maxExpiry) {
}
boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount == maxNumRetries) {
return false;
}else {
long nextBackOffDelay = initialExpiry * Math.pow(backOffRate, executionCount -
1)
long delay = Math.min(maxExpiry, nextBackOffDelay)
Thread.sleep(delay);
return true;
}
}
}
此外,为了触发重试,您需要添加一个响应拦截器来抛出IOException
, e.g :
class MyResponseInterceptor extends HttpResponseInterceptor {
void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
if (response.getStatusLine.getStatusCode == 503) {
throw new IOException("Please retry")
}
}
}
最后,您可以构建 HTTP 客户端实例,如下所示:
HttpClientBuilder
.create()
.setRetryHandler(new MyExponentialBackoffRetryHandler(...))
.addInterceptorFirst(new MyResponseInterceptor())
.build()
您可以通过发送请求来轻松测试客户端https://httpstat.us/503