美文网首页
HttpClient 失败重试机制

HttpClient 失败重试机制

作者: 杨康他兄弟 | 来源:发表于2019-11-22 16:21 被阅读0次
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>

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();

相关文章

网友评论

      本文标题:HttpClient 失败重试机制

      本文链接:https://www.haomeiwen.com/subject/bodqwctx.html