我是靠谱客的博主 淡定春天,这篇文章主要介绍HttpClient重试机制,现在分享给大家,希望可以做个参考。

 通过http做接口调用请求的时候,常常会因为网络抖动或者其他未知原因,造成接口在某个瞬间访问不了。此时需要增加重试机制。

private static HttpRequestRetryHandler httpRequestRetryHandler =null;

    static {
        httpRequestRetryHandler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int retryTimes, HttpContext context) {
                logger.error("retryRequest:"+retryTimes);
                if (retryTimes >= 3) {
                    return false;
                }
                if (exception instanceof ConnectTimeoutException || exception instanceof NoHttpResponseException || exception instanceof SocketTimeoutException
                        || !(exception instanceof UnknownHostException) || !(exception instanceof InterruptedIOException) || !(exception instanceof SSLException)
                        || !(exception instanceof SSLHandshakeException)) {
                    return true;
                }else {
                    logger.error("未记录的请求异常:" + exception.getClass());
                }

                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // 如果请求被认为是幂等的,那么就重试。即重复执行不影响程序其他效果的
                    return true;
                }
                return false;
            }
        };
    }

public static CloseableHttpClient createSSLClientDefault(Boolean bool) {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            if (bool)
                return HttpClients.custom().setRetryHandler(httpRequestRetryHandler).setSSLSocketFactory(sslsf).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpClients.custom().setRetryHandler(httpRequestRetryHandler).build();
        //.setConnectionManager(connectionManager).setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
    }



 public static String userPost(String url, String token,String jsonString){

    CloseableHttpClient httpClient = createSSLClientDefault(StringUtils.isNotBlank(url) && url.startsWith("https"));
    ...
}

最后

以上就是淡定春天最近收集整理的关于HttpClient重试机制的全部内容,更多相关HttpClient重试机制内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(136)

评论列表共有 0 条评论

立即
投稿
返回
顶部