java 失败重试策略_HttpClient 失败重试机制

org.apache.httpcomponents

httpclient

4.5.1

HttpClient的异常分两类

java.io.IOException

HttpException

其中,java.io.IOException认为是非致命,可恢复的。HttpException认为是致命不可恢复的。

对于 java.io.IOException异常,我们想要重试,就需要实现HttpClient提供的HttpRequestRetryHandler 接口。

实现如下:

HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

public boolean retryRequest(

IOException exception,

int executionCount,

HttpContext context) {

if (executionCount >= 5) {

// Do not retry if over max retry count

return false;

}

if (exception instanceof InterruptedIOException) {

// Timeout

return false;

}

if (exception instanceof UnknownHostException) {

// Unknown host

return false;

}

if (exception instanceof ConnectTimeoutException) {

// Connection refused

return false;

}

if (exception instanceof SSLException) {

// SSL handshake exception

return false;

}

HttpClientContext clientContext = HttpClientContext.adapt(context);

HttpRequest request = clientContext.getRequest();

boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);

if (idempotent) {

// Retry if the request is considered idempotent

return true;

}

return false;

}

};

CloseableHttpClient httpclient = HttpClients.custom()

.setRetryHandler(myRetryHandler)

.build();


版权声明:本文为weixin_35934226原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。