分享

spring集成httpclient连接池配置

 land_zhj 2017-03-27

spring与httpclient集成方式如下:

1.引入jar包;

  1. <dependency>  
  2.     <groupId>org.apache.httpcomponents</groupId>  
  3.     <artifactId>httpclient</artifactId>  
  4.     <version>4.5.2</version>  
  5. </dependency>  

2.使用一个单独的线程完成连接池中的无效链接的清理

  1. package com.wee.common.httpclient;  
  2.   
  3. import org.apache.http.conn.HttpClientConnectionManager;  
  4.   
  5. public class IdleConnectionEvictor extends Thread {  
  6.   
  7.     private final HttpClientConnectionManager connMgr;  
  8.   
  9.     private volatile boolean shutdown;  
  10.   
  11.     public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {  
  12.         this.connMgr = connMgr;  
  13.         // 启动当前线程  
  14.         this.start();  
  15.     }  
  16.   
  17.     @Override  
  18.     public void run() {  
  19.         try {  
  20.             while (!shutdown) {  
  21.                 synchronized (this) {  
  22.                     wait(5000);  
  23.                     // 关闭失效的连接  
  24.                     connMgr.closeExpiredConnections();  
  25.                 }  
  26.             }  
  27.         } catch (InterruptedException ex) {  
  28.             // 结束  
  29.         }  
  30.     }  
  31.   
  32.     public void shutdown() {  
  33.         shutdown = true;  
  34.         synchronized (this) {  
  35.             notifyAll();  
  36.         }  
  37.     }  
  38. }  
3.spring和httpClient整合配置文件

  1. <!-- 定义连接管理器 -->  
  2.     <bean id="httpClientConnectionManager"  
  3.         class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"  
  4.         destroy-method="close">  
  5.         <!-- 最大连接数 -->  
  6.         <property name="maxTotal" value="${http.maxTotal}" />  
  7.   
  8.         <!-- 设置每个主机地址的并发数 -->  
  9.         <property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />  
  10.     </bean>  
  11.   
  12.     <!-- httpclient对象构建器 -->  
  13.     <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">  
  14.         <!-- 设置连接管理器 -->  
  15.         <property name="connectionManager" ref="httpClientConnectionManager" />  
  16.     </bean>  
  17.   
  18.     <!-- 定义Httpclient对象 -->  
  19.     <bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"  
  20.         factory-bean="httpClientBuilder" factory-method="build" scope="prototype">  
  21.     </bean>  
  22.   
  23.     <!-- 定义清理无效连接 -->  
  24.     <bean class="com.taotao.common.httpclient.IdleConnectionEvictor"  
  25.         destroy-method="shutdown">  
  26.         <constructor-arg index="0" ref="httpClientConnectionManager" />  
  27.     </bean>  
  28.   
  29.     <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">  
  30.         <!-- 创建连接的最长时间 -->  
  31.         <property name="connectTimeout" value="${http.connectTimeout}"/>  
  32.         <!-- 从连接池中获取到连接的最长时间 -->  
  33.         <property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}"/>  
  34.         <!-- 数据传输的最长时间 -->  
  35.         <property name="socketTimeout" value="${http.socketTimeout}"/>  
  36.         <!-- 提交请求前测试连接是否可用 -->  
  37.         <property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}"/>  
  38.     </bean>  
  39.     <!-- 定义请求参数 -->  
  40.     <bean id="requestConfig" class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder" factory-method="build">  
  41.     </bean>  

4.httpclient.properties
  1. httpClient.maxTotal=200  
  2. httpClient.defaultMaxPerRoute=50  
  3. httpClient.connectTimeout=1000  
  4. httpClient.connectionRequestTimeout=500  
  5. httpClient.socketTimeout=10000  
  6. httpClient.staleConnectionCheckEnabled=true  
5.编写执行get和post请求的java类

  1. package com.wee.common.service;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.URISyntaxException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.apache.http.NameValuePair;  
  10. import org.apache.http.client.ClientProtocolException;  
  11. import org.apache.http.client.config.RequestConfig;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.CloseableHttpResponse;  
  14. import org.apache.http.client.methods.HttpGet;  
  15. import org.apache.http.client.methods.HttpPost;  
  16. import org.apache.http.client.utils.URIBuilder;  
  17. import org.apache.http.entity.ContentType;  
  18. import org.apache.http.entity.StringEntity;  
  19. import org.apache.http.impl.client.CloseableHttpClient;  
  20. import org.apache.http.message.BasicNameValuePair;  
  21. import org.apache.http.util.EntityUtils;  
  22. import org.springframework.beans.factory.annotation.Autowired;  
  23. import org.springframework.stereotype.Service;  
  24.   
  25. import com.wee.common.bean.HttpResult;  
  26.   
  27. @Service  
  28. public class HttpClientService {  
  29.   
  30.     @Autowired  
  31.     private CloseableHttpClient httpClient;  
  32.     @Autowired  
  33.     private RequestConfig requestConfig;  
  34.   
  35.     /** 
  36.      * 执行GET请求 
  37.      *  
  38.      * @param url 
  39.      * @return 
  40.      * @throws IOException 
  41.      * @throws ClientProtocolException 
  42.      */  
  43.     public String doGet(String url) throws ClientProtocolException, IOException {  
  44.         // 创建http GET请求  
  45.         HttpGet httpGet = new HttpGet(url);  
  46.         httpGet.setConfig(this.requestConfig);  
  47.   
  48.         CloseableHttpResponse response = null;  
  49.         try {  
  50.             // 执行请求  
  51.             response = httpClient.execute(httpGet);  
  52.             // 判断返回状态是否为200  
  53.             if (response.getStatusLine().getStatusCode() == 200) {  
  54.                 return EntityUtils.toString(response.getEntity(), "UTF-8");  
  55.             }  
  56.         } finally {  
  57.             if (response != null) {  
  58.                 response.close();  
  59.             }  
  60.         }  
  61.         return null;  
  62.     }  
  63.   
  64.     /** 
  65.      * 带有参数的GET请求 
  66.      *  
  67.      * @param url 
  68.      * @param params 
  69.      * @return 
  70.      * @throws URISyntaxException 
  71.      * @throws IOException 
  72.      * @throws ClientProtocolException 
  73.      */  
  74.     public String doGet(String url, Map<String, String> params)  
  75.             throws ClientProtocolException, IOException, URISyntaxException {  
  76.         URIBuilder uriBuilder = new URIBuilder(url);  
  77.         for (String key : params.keySet()) {  
  78.             uriBuilder.addParameter(key, params.get(key));  
  79.         }  
  80.         return this.doGet(uriBuilder.build().toString());  
  81.     }  
  82.   
  83.     /** 
  84.      * 执行POST请求 
  85.      *  
  86.      * @param url 
  87.      * @param params 
  88.      * @return 
  89.      * @throws IOException 
  90.      */  
  91.     public HttpResult doPost(String url, Map<String, String> params) throws IOException {  
  92.         // 创建http POST请求  
  93.         HttpPost httpPost = new HttpPost(url);  
  94.         httpPost.setConfig(this.requestConfig);  
  95.         if (params != null) {  
  96.             // 设置2个post参数,一个是scope、一个是q  
  97.             List<NameValuePair> parameters = new ArrayList<NameValuePair>();  
  98.             for (String key : params.keySet()) {  
  99.                 parameters.add(new BasicNameValuePair(key, params.get(key)));  
  100.             }  
  101.             // 构造一个form表单式的实体  
  102.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");  
  103.             // 将请求实体设置到httpPost对象中  
  104.             httpPost.setEntity(formEntity);  
  105.         }  
  106.   
  107.         CloseableHttpResponse response = null;  
  108.         try {  
  109.             // 执行请求  
  110.             response = httpClient.execute(httpPost);  
  111.             return new HttpResult(response.getStatusLine().getStatusCode(),  
  112.                     EntityUtils.toString(response.getEntity(), "UTF-8"));  
  113.         } finally {  
  114.             if (response != null) {  
  115.                 response.close();  
  116.             }  
  117.         }  
  118.     }  
  119.   
  120.     /** 
  121.      * 执行POST请求 
  122.      *  
  123.      * @param url 
  124.      * @return 
  125.      * @throws IOException 
  126.      */  
  127.     public HttpResult doPost(String url) throws IOException {  
  128.         return this.doPost(url, null);  
  129.     }  
  130.   
  131.     /** 
  132.      * 提交json数据 
  133.      *  
  134.      * @param url 
  135.      * @param json 
  136.      * @return 
  137.      * @throws ClientProtocolException 
  138.      * @throws IOException 
  139.      */  
  140.     public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {  
  141.         // 创建http POST请求  
  142.         HttpPost httpPost = new HttpPost(url);  
  143.         httpPost.setConfig(this.requestConfig);  
  144.   
  145.         if (json != null) {  
  146.             // 构造一个form表单式的实体  
  147.             StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);  
  148.             // 将请求实体设置到httpPost对象中  
  149.             httpPost.setEntity(stringEntity);  
  150.         }  
  151.   
  152.         CloseableHttpResponse response = null;  
  153.         try {  
  154.             // 执行请求  
  155.             response = this.httpClient.execute(httpPost);  
  156.             return new HttpResult(response.getStatusLine().getStatusCode(),  
  157.                     EntityUtils.toString(response.getEntity(), "UTF-8"));  
  158.         } finally {  
  159.             if (response != null) {  
  160.                 response.close();  
  161.             }  
  162.         }  
  163.     }  
  164.   
  165. }  

 HttpResult.java

  1. public class HttpResult {  
  2.   
  3.     /** 
  4.      * 状态码 
  5.      */  
  6.     private Integer status;  
  7.     /** 
  8.      * 返回数据 
  9.      */  
  10.     private String data;  
  11.   
  12.     public HttpResult() {  
  13.     }  
  14.   
  15.     public HttpResult(Integer status, String data) {  
  16.         this.status = status;  
  17.         this.data = data;  
  18.     }  
  19.   
  20.     public Integer getStatus() {  
  21.         return status;  
  22.     }  
  23.   
  24.     public void setStatus(Integer status) {  
  25.         this.status = status;  
  26.     }  
  27.   
  28.     public String getData() {  
  29.         return data;  
  30.     }  
  31.   
  32.     public void setData(String data) {  
  33.         this.data = data;  
  34.     }  
  35.   
  36. }  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多