httpClient 4.5.2 实现连接池

来源:互联网 发布:软件著作权的申请 编辑:程序博客网 时间:2024/05/17 23:10
如下代码
[java] view plain copy
  1. public class PoolHttpsClientService {  
  2.   
  3.   
  4.     // 日志  
  5.     private static final SimpleLogger LOGGER = SimpleLogger.getLogger(PoolHttpsClientService.class);  
  6.   
  7.   
  8.     private static final String CHAR_SET = "UTF-8";  
  9.   
  10.   
  11.     // 代理IP  
  12.     @Value("${InetAddressStr}")  
  13.     private String InetAddressStr;  
  14.   
  15.   
  16.     // 代理端口  
  17.     @Value("${InetPort}")  
  18.     private int InetPort;  
  19.   
  20.   
  21.     /** 
  22.      * 最大连接数400 
  23.      */  
  24.     private static int MAX_CONNECTION_NUM = 400;  
  25.   
  26.   
  27.     /** 
  28.      * 单路由最大连接数80 
  29.      */  
  30.     private static int MAX_PER_ROUTE = 80;  
  31.   
  32.   
  33.     /** 
  34.      * 向服务端请求超时时间设置(单位:毫秒) 
  35.      */  
  36.     private static int SERVER_REQUEST_TIME_OUT = 2000;  
  37.   
  38.   
  39.     /** 
  40.      * 服务端响应超时时间设置(单位:毫秒) 
  41.      */  
  42.     private static int SERVER_RESPONSE_TIME_OUT = 2000;  
  43.   
  44.   
  45.     /** 
  46.      * 构造函数 
  47.      */  
  48.     private PoolHttpsClientService() {  
  49.     }  
  50.   
  51.   
  52.     private static Object LOCAL_LOCK = new Object();  
  53.       
  54.     /** 
  55.      * 连接池管理对象 
  56.      */  
  57.     PoolingHttpClientConnectionManager cm = null;  
  58.   
  59.   
  60.     /** 
  61.      *  
  62.      * 功能描述: <br> 
  63.      * 初始化连接池管理对象 
  64.      * 
  65.      * @see [相关类/方法](可选) 
  66.      * @since [产品/模块版本](可选) 
  67.      */  
  68.     private PoolingHttpClientConnectionManager getPoolManager() {  
  69.         final String methodName = "getPoolManager";  
  70.         LOGGER.enter(methodName, "initPoolManager");  
  71.         if (null == cm) {  
  72.             synchronized (LOCAL_LOCK) {  
  73.                 if (null == cm) {  
  74.                     SSLContextBuilder sslContextBuilder = new SSLContextBuilder();  
  75.                     try {  
  76.                         sslContextBuilder.loadTrustMaterial(nullnew TrustSelfSignedStrategy());  
  77.                         SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(  
  78.                                 sslContextBuilder.build());  
  79.                         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()  
  80.                                 .register("https", socketFactory)  
  81.                                 .register("http"new PlainConnectionSocketFactory())  
  82.                                 .build();  
  83.                         cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  84.                         cm.setMaxTotal(MAX_CONNECTION_NUM);  
  85.                         cm.setDefaultMaxPerRoute(MAX_PER_ROUTE);  
  86.                     } catch (Exception e) {  
  87.                         LOGGER.error(methodName, "init PoolingHttpClientConnectionManager Error" + e);  
  88.                     }  
  89.   
  90.   
  91.                 }  
  92.             }  
  93.         }  
  94.         LOGGER.exit(methodName, "initPoolManager");  
  95.         return cm;  
  96.     }  
  97.   
  98.   
  99.     /** 
  100.      * 创建线程安全的HttpClient 
  101.      *  
  102.      * @param config 客户端超时设置 
  103.      *  
  104.      * @return 
  105.      */  
  106.     public CloseableHttpClient getHttpsClient(RequestConfig config) {  
  107.         final String methodName = "getHttpsClient";  
  108.         LOGGER.enter(methodName, "initHttpsClient");  
  109.         CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config)  
  110.                 .setConnectionManager(this.getPoolManager())  
  111.                 .build();  
  112.         LOGGER.exit(methodName, "initHttpsClient");  
  113.         return httpClient;  
  114.     }  
  115.   
  116.   
  117.     /** 
  118.      * Https post请求 
  119.      *  
  120.      * @param url 请求地址 
  121.      * @param json 请求参数(如果为null,则表示不请求参数) return 返回结果 
  122.      */  
  123.     public String poolHttpsPost(String url, JSONObject json) {  
  124.         final String methodName = "poolHttpsPost";  
  125.         LOGGER.enter(methodName, json);  
  126.         CloseableHttpResponse response = null;  
[java] view plain copy
  1.             HttpPost post = null;  
  2.         try {  
  3.             // 设置代理  
  4.             HttpHost proxy = new HttpHost(InetAddressStr, InetPort);  
  5.             // connectTimeout设置服务器请求超时时间  
  6.             // socketTimeout设置服务器响应超时时间  
  7.             RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy)  
  8.                     .setSocketTimeout(SERVER_REQUEST_TIME_OUT).setConnectTimeout(SERVER_RESPONSE_TIME_OUT).build();  
  9.             post = new HttpPost(url);  
  10.             post.setConfig(requestConfig);  
  11.   
  12.   
  13.             if (json != null) {  
  14.                 StringEntity se = new StringEntity(json.toString(), CHAR_SET);  
  15.                 se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;"));  
  16.                 post.setEntity(se);  
  17.             }  
  18.   
  19.   
  20.             LOGGER.info(methodName, "start post to weixin");  
  21.             response = getHttpsClient(requestConfig).execute(post);  
  22.             LOGGER.info(methodName, "end post to weixin");  
  23.             int status = response.getStatusLine().getStatusCode();  
  24.             LOGGER.info(methodName, "return status:" + status);  
  25.   
  26.   
  27.             String result = null;  
  28.             if (status == 200) {  
  29.                 result = EntityUtils.toString(response.getEntity(), CHAR_SET);  
  30.             }  
  31.             EntityUtils.consume(response.getEntity());  
  32.             response.close();  
  33.             LOGGER.exit(methodName);  
  34.             return result;  
  35.         } catch (Exception e) {  
  36.             if (e instanceof SocketTimeoutException) {  
  37.                 // 服务器请求超时  
  38.                 LOGGER.error(methodName, "server request time out");  
  39.             } else if (e instanceof ConnectTimeoutException) {  
  40.                 // 服务器响应超时(已经请求了)  
  41.                 LOGGER.error(methodName, "server response time out");  
  42.             }  
  43.             LOGGER.error(methodName, e.getMessage());  
  44.         } finally {  
[java] view plain copy
  1.                   post.releaseConnection();  
  2.             if (response != null) {  
  3.                 try {  
  4.                     EntityUtils.consume(response.getEntity());  
  5.                     response.close();  
  6.                 } catch (IOException e) {  
  7.                     LOGGER.error(methodName, e.getMessage());  
  8.                 }  
  9.             }  
  10.         }  
  11.         LOGGER.exit(methodName);  
  12.         // 超时或者网络不通时返回值  
  13.         return null;  
  14.     }  
0 0
原创粉丝点击