美文网首页
HttpClient连接池配置和连接失败重试机制

HttpClient连接池配置和连接失败重试机制

作者: 窗外星河低悬im | 来源:发表于2021-10-19 14:55 被阅读0次

为了解决http频繁连接,以及连接超时的问题,使用该配置。

import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * 描述:
 *
 * @author sophia
 * @date 2021/10/18  11:47
 */
public class HttpClientUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
    // 池化管理
    private static PoolingHttpClientConnectionManager poolConnManager = null;
    // 它是线程安全的,所有的线程都可以使用它一起发送http请求
    private static CloseableHttpClient httpClient;
    private static final int DEFAULT_TOTAL = 20;
    private static final int MAX_TOTAL = 100;
    private static final int CONNECTION_TIMEOUT = 3000;
    private static final int CONNECTION_REQUEST_TIMEOUT = 5000;
    private static final int SOCKET_TIMEOUT = 60000 * 5;
    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry =
                    RegistryBuilder.<ConnectionSocketFactory>create().
                            register("http", PlainConnectionSocketFactory.getSocketFactory()).
                            register("https", sslsf).build();
            // 初始化连接管理器
            poolConnManager
                    = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            poolConnManager.setMaxTotal(MAX_TOTAL);// 同时最多连接数
            // 设置最大路由
            poolConnManager.setDefaultMaxPerRoute(DEFAULT_TOTAL);
            // 初始化httpClient
            httpClient = getConnection();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    public static CloseableHttpClient getConnection() {
        //设置连接超时初始值
        RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                //设置连接池管理
                .setConnectionManager(poolConnManager)
                .setRetryHandler((exception, executionCount, context) -> {
                    if (executionCount > 3) {
                        LOGGER.warn("Maximum tries reached for client http pool ");
                        return false;
                    }
                    //NoHttpResponseException 重试
                    if (exception instanceof NoHttpResponseException
                        || exception instanceof ConnectTimeoutException //连接超时重试
                    ) {
                        LOGGER.warn("NoHttpResponseException on " + executionCount + " call");
                        return true;
                    }
                    return false;
                }).build();
        return httpClient;
    }

    public static CloseableHttpClient getHttpClient() {
        return httpClient;
    }
}

相关文章

网友评论

      本文标题:HttpClient连接池配置和连接失败重试机制

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