package com.sunxung.factoring.component.util;


import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.charset.Charset;

/**
 * @Description : closeabletHttpClient工具类
 * @Author : L.Jia
 * @Date: 2023-03-04 12:33
 */
public class CloseableHttpClientUtils {

    private static Logger logger = LogManager.getLogger(CloseableHttpClientUtils.class);

    private static CloseableHttpClient httpClient = null;

    private static final Charset CHAR_SET = Charset.forName("utf-8");
    private static PoolingHttpClientConnectionManager cm;

    public CloseableHttpClientUtils() {
        init();
    }

    public void init() {
        cm = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        cm.setMaxTotal(50);
        //设置每个主机地址的并发数
        //cm.setDefaultMaxPerRoute(100);
        cm.setDefaultConnectionConfig(ConnectionConfig.custom()
                .setCharset(CHAR_SET).build());
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(30000)
                .setSoReuseAddress(true).build();
        cm.setDefaultSocketConfig(socketConfig);
        httpClient = HttpClientBuilder.create().setConnectionManager(cm)
                .build();
    }


    public static CloseableHttpClient getHttpClient() {

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(20 * 1000) //设置连接超时时间，单位毫秒
                //.setConnectionRequestTimeout(timeout * 1000) //设置从connect Manager获取Connection 超时时间，单位毫秒
                .setSocketTimeout(20 * 1000).build(); //请求获取数据的超时时间，单位毫秒
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                //.setDefaultRequestConfig(config) //使用此方法连接池会关闭
                .setConnectionManagerShared(true)
                .build();
        if (cm != null && cm.getTotalStats() != null) { //打印连接池的状态
            logger.info("now client pool {}" + cm.getTotalStats().toString());
        }
        return httpClient;
    }
}
