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"));
    ...
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值