httpClient 4.5.2 实现连接池

如下代码
public class PoolHttpsClientService {


    // 日志
    private static final SimpleLogger LOGGER = SimpleLogger.getLogger(PoolHttpsClientService.class);


    private static final String CHAR_SET = "UTF-8";


    // 代理IP
    @Value("${InetAddressStr}")
    private String InetAddressStr;


    // 代理端口
    @Value("${InetPort}")
    private int InetPort;


    /**
     * 最大连接数400
     */
    private static int MAX_CONNECTION_NUM = 400;


    /**
     * 单路由最大连接数80
     */
    private static int MAX_PER_ROUTE = 80;


    /**
     * 向服务端请求超时时间设置(单位:毫秒)
     */
    private static int SERVER_REQUEST_TIME_OUT = 2000;


    /**
     * 服务端响应超时时间设置(单位:毫秒)
     */
    private static int SERVER_RESPONSE_TIME_OUT = 2000;


    /**
     * 构造函数
     */
    private PoolHttpsClientService() {
    }


    private static Object LOCAL_LOCK = new Object();
    
    /**
     * 连接池管理对象
     */
    PoolingHttpClientConnectionManager cm = null;


    /**
     * 
     * 功能描述: 
     * 初始化连接池管理对象      *      * @see [相关类/方法](可选)      * @since [产品/模块版本](可选)      */     private PoolingHttpClientConnectionManager getPoolManager() {         final String methodName = "getPoolManager";         LOGGER.enter(methodName, "initPoolManager");         if (null == cm) {             synchronized (LOCAL_LOCK) {                 if (null == cm) {                     SSLContextBuilder sslContextBuilder = new SSLContextBuilder();                     try {                         sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());                         SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(                                 sslContextBuilder.build());                         Registry socketFactoryRegistry = RegistryBuilder. create()                                 .register("https", socketFactory)                                 .register("http", new PlainConnectionSocketFactory())                                 .build();                         cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);                         cm.setMaxTotal(MAX_CONNECTION_NUM);                         cm.setDefaultMaxPerRoute(MAX_PER_ROUTE);                     } catch (Exception e) {                         LOGGER.error(methodName, "init PoolingHttpClientConnectionManager Error" + e);                     }                 }             }         }         LOGGER.exit(methodName, "initPoolManager");         return cm;     }     /**      * 创建线程安全的HttpClient      *       * @param config 客户端超时设置      *       * @return      */     public CloseableHttpClient getHttpsClient(RequestConfig config) {         final String methodName = "getHttpsClient";         LOGGER.enter(methodName, "initHttpsClient");         CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config)                 .setConnectionManager(this.getPoolManager())                 .build();         LOGGER.exit(methodName, "initHttpsClient");         return httpClient;     }     /**      * Https post请求      *       * @param url 请求地址      * @param json 请求参数(如果为null,则表示不请求参数) return 返回结果      */     public String poolHttpsPost(String url, JSONObject json) {         final String methodName = "poolHttpsPost";         LOGGER.enter(methodName, json);         CloseableHttpResponse response = null;
            HttpPost post = null;
        try {
            // 设置代理
            HttpHost proxy = new HttpHost(InetAddressStr, InetPort);
            // connectTimeout设置服务器请求超时时间
            // socketTimeout设置服务器响应超时时间
            RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy)
                    .setSocketTimeout(SERVER_REQUEST_TIME_OUT).setConnectTimeout(SERVER_RESPONSE_TIME_OUT).build();
            post = new HttpPost(url);
            post.setConfig(requestConfig);


            if (json != null) {
                StringEntity se = new StringEntity(json.toString(), CHAR_SET);
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;"));
                post.setEntity(se);
            }


            LOGGER.info(methodName, "start post to weixin");
            response = getHttpsClient(requestConfig).execute(post);
            LOGGER.info(methodName, "end post to weixin");
            int status = response.getStatusLine().getStatusCode();
            LOGGER.info(methodName, "return status:" + status);


            String result = null;
            if (status == 200) {
                result = EntityUtils.toString(response.getEntity(), CHAR_SET);
            }
            EntityUtils.consume(response.getEntity());
            response.close();
            LOGGER.exit(methodName);
            return result;
        } catch (Exception e) {
            if (e instanceof SocketTimeoutException) {
                // 服务器请求超时
                LOGGER.error(methodName, "server request time out");
            } else if (e instanceof ConnectTimeoutException) {
                // 服务器响应超时(已经请求了)
                LOGGER.error(methodName, "server response time out");
            }
            LOGGER.error(methodName, e.getMessage());
        } finally {
                  post.releaseConnection();
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    LOGGER.error(methodName, e.getMessage());
                }
            }
        }
        LOGGER.exit(methodName);
        // 超时或者网络不通时返回值
        return null;
    }


 
 

你可能感兴趣的:(httpClient 4.5.2 实现连接池)