Http请求连接池 - HttpClient 的 PoolingHttpClientConnectionManager

http://blog.csdn.net/catoop/article/details/50352334

http://sharong.iteye.com/blog/2250777

只有一个httpclient的实例,你可以看看CloseableHttpClient和PoolingHttpClientConnectionManager的源码,你会发现httpclient实例通过execute执行get或post获取连接的时候,会通过实例关联的connectionManager的connect()来建立连接,这里的connectionManager是一个连接池的实现, 因此connect方法调用的是PoolingHttpClientConnectionManager重写的实现,这就是一个连接池建立连接的实现,具体还是看源码吧

HttpClient 3.x,4.x都提供http连接池管理器,当使用了请求连接池管理器(比如PoolingHttpClientConnectionManager)后,HttpClient就可以同时执行多个线程的请求了。 

hc3.x和4.x的早期版本,提供了PoolingClientConnectionManager,DefaultHttpClient等类来实现http连接池,但这些类在4.3.x版本之后大部分就已经过时,本文使用4.3.x提供的最新的PoolingHttpClientConnectionManager等类进行http连接池的实现. 
废话不多说,下面是全部代码: 

Java代码   收藏代码
  1. public class PoolTest {  
  2.     private static void config(HttpRequestBase httpRequestBase) {  
  3.         httpRequestBase.setHeader("User-Agent""Mozilla/5.0");  
  4.         httpRequestBase.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");  
  5.         httpRequestBase.setHeader("Accept-Language""zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");  
  6.         httpRequestBase.setHeader("Accept-Charset""ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");  
  7.           
  8.         // 配置请求的超时设置  
  9.         RequestConfig requestConfig = RequestConfig.custom()  
  10.                 .setConnectionRequestTimeout(3000)  
  11.                 .setConnectTimeout(3000)  
  12.                 .setSocketTimeout(3000)  
  13.                 .build();  
  14.         httpRequestBase.setConfig(requestConfig);         
  15.     }  
  16.   
  17.     public static void main(String[] args) {  
  18.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  19.         LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();  
  20.         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()  
  21.                 .register("http", plainsf)  
  22.                 .register("https", sslsf)  
  23.                 .build();  
  24.   
  25.         PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);  
  26.         // 将最大连接数增加到200  
  27.         cm.setMaxTotal(200);  
  28.         // 将每个路由基础的连接增加到20  
  29.         cm.setDefaultMaxPerRoute(20);  
  30.   
  31.         // 将目标主机的最大连接数增加到50  
  32.         HttpHost localhost = new HttpHost("http://blog.csdn.net/gaolu",80);  
  33.         cm.setMaxPerRoute(new HttpRoute(localhost), 50);  
  34.           
  35.         //请求重试处理  
  36.         HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {  
  37.             public boolean retryRequest(IOException exception,int executionCount, HttpContext context) {  
  38.                 if (executionCount >= 5) {// 如果已经重试了5次,就放弃                     
  39.                     return false;  
  40.                 }  
  41.                 if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试                    
  42.                     return true;  
  43.                 }  
  44.                 if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常                   
  45.                     return false;  
  46.                 }                 
  47.                 if (exception instanceof InterruptedIOException) {// 超时                   
  48.                     return false;  
  49.                 }  
  50.                 if (exception instanceof UnknownHostException) {// 目标服务器不可达                   
  51.                     return false;  
  52.                 }  
  53.                 if (exception instanceof ConnectTimeoutException) {// 连接被拒绝                   
  54.                     return false;  
  55.                 }  
  56.                 if (exception instanceof SSLException) {// ssl握手异常                    
  57.                     return false;  
  58.                 }  
  59.                   
  60.                 HttpClientContext clientContext = HttpClientContext.adapt(context);  
  61.                 HttpRequest request = clientContext.getRequest();  
  62.                 // 如果请求是幂等的,就再次尝试  
  63.                 if (!(request instanceof HttpEntityEnclosingRequest)) {                   
  64.                     return true;  
  65.                 }  
  66.                 return false;  
  67.             }  
  68.         };    
  69.           
  70.         CloseableHttpClient httpClient = HttpClients.custom()  
  71.                 .setConnectionManager(cm)  
  72.                 .setRetryHandler(httpRequestRetryHandler)  
  73.                 .build();  
  74.   
  75.         // URL列表数组  
  76.         String[] urisToGet = {        
  77.                 "http://blog.csdn.net/gaolu/article/details/48466059",  
  78.                 "http://blog.csdn.net/gaolu/article/details/48243103",  
  79.                 "http://blog.csdn.net/gaolu/article/details/47656987",  
  80.                 "http://blog.csdn.net/gaolu/article/details/47055029",  
  81.                   
  82.                 "http://blog.csdn.net/gaolu/article/details/46400883",  
  83.                 "http://blog.csdn.net/gaolu/article/details/46359127",  
  84.                 "http://blog.csdn.net/gaolu/article/details/46224821",  
  85.                 "http://blog.csdn.net/gaolu/article/details/45305769",  
  86.                   
  87.                 "http://blog.csdn.net/gaolu/article/details/43701763",  
  88.                 "http://blog.csdn.net/gaolu/article/details/43195449",  
  89.                 "http://blog.csdn.net/gaolu/article/details/42915521",  
  90.                 "http://blog.csdn.net/gaolu/article/details/41802319",  
  91.                   
  92.                 "http://blog.csdn.net/gaolu/article/details/41045233",  
  93.                 "http://blog.csdn.net/gaolu/article/details/40395425",  
  94.                 "http://blog.csdn.net/gaolu/article/details/40047065",  
  95.                 "http://blog.csdn.net/gaolu/article/details/39891877",  
  96.                   
  97.                 "http://blog.csdn.net/gaolu/article/details/39499073",  
  98.                 "http://blog.csdn.net/gaolu/article/details/39314327",  
  99.                 "http://blog.csdn.net/gaolu/article/details/38820809",  
  100.                 "http://blog.csdn.net/gaolu/article/details/38439375",  
  101.         };  
  102.           
  103.         long start = System.currentTimeMillis();          
  104.         try {  
  105.             int pagecount = urisToGet.length;  
  106.             ExecutorService executors = Executors.newFixedThreadPool(pagecount);  
  107.             CountDownLatch countDownLatch = new CountDownLatch(pagecount);        
  108.             for(int i = 0; i< pagecount;i++){  
  109.                 HttpGet httpget = new HttpGet(urisToGet[i]);  
  110.                 config(httpget);  
  111.   
  112.                 //启动线程抓取  
  113.                 executors.execute(new GetRunnable(httpClient,httpget,countDownLatch));  
  114.             }  
  115.   
  116.             countDownLatch.await();  
  117.             executors.shutdown();  
  118.         } catch (InterruptedException e) {  
  119.             e.printStackTrace();  
  120.         } finally {  
  121.             System.out.println("线程" + Thread.currentThread().getName() + "," + System.currentTimeMillis() + ", 所有线程已完成,开始进入下一步!");  
  122.         }         
  123.           
  124.         long end = System.currentTimeMillis();  
  125.         System.out.println("consume -> " + (end - start));  
  126.     }  
  127.       
  128.     static class GetRunnable implements Runnable {  
  129.         private CountDownLatch countDownLatch;  
  130.         private final CloseableHttpClient httpClient;  
  131.         private final HttpGet httpget;  
  132.           
  133.         public GetRunnable(CloseableHttpClient httpClient, HttpGet httpget, CountDownLatch countDownLatch){  
  134.             this.httpClient = httpClient;  
  135.             this.httpget = httpget;  
  136.               
  137.             this.countDownLatch = countDownLatch;  
  138.         }  
  139.   
  140.         @Override  
  141.         public void run() {  
  142.             CloseableHttpResponse response = null;  
  143.             try {  
  144.                 response = httpClient.execute(httpget,HttpClientContext.create());  
  145.                 HttpEntity entity = response.getEntity();  
  146.                 System.out.println(EntityUtils.toString(entity, "utf-8")) ;  
  147.                 EntityUtils.consume(entity);  
  148.             } catch (IOException e) {  
  149.                 e.printStackTrace();  
  150.             } finally {  
  151.                 countDownLatch.countDown();  
  152.                   
  153.                 try {  
  154.                     if(response != null)  
  155.                         response.close();  
  156.                 } catch (IOException e) {  
  157.                     e.printStackTrace();  
  158.                 }  
  159.             }  
  160.         }  
  161.     }     
  162. }  

主要参考文档: 
http://free0007.iteye.com/blog/2012308 

一开始我是使用传统的 HttpURLConnection 来做网络请求的,查了很多资料,有不少说 HttpURLConnection 效率高的。可是经过我修改实现方法后,HttpClient 连接池版本的网络请求相对比较稳定。这也说明,我们并不请尽信他人解说,凡事还是要寻找适合自己的方法,真正的解决自己的问题,才是王道。

===========================================

在使用 HttpURLConnection 的时候,大并发对外做网络请求的时候,前期请求耗时还好,后面耗时越来越高。下面是我之前的实现代码:

    @Deprecated
    protected JSONObject callRestfulOld(String url, Map<String, Object> params) 
    {
        String temp;
        String ret="";
        JSONObject jsonRet=null;
        String sign = generateSign("POST", url, params);// 对参数进行加密签名
        if(sign.isEmpty()) return new JSONObject("{\"ret_code\":-1,\"err_msg\":\"generateSign error\"}");
        params.put("sign", sign);
        try{
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)u.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            StringBuffer param = new StringBuffer();
            for (String key: params.keySet())
            {
                param.append(key).append("=").append(URLEncoder.encode(params.get(key).toString(), "UTF-8")).append("&");
            }
            conn.getOutputStream().write(param.toString().getBytes("UTF-8"));

            //System.out.println(param);
            conn.getOutputStream().flush();
            conn.getOutputStream().close();
            InputStreamReader isr = new InputStreamReader(conn.getInputStream());  
            BufferedReader br = new BufferedReader(isr);  
            while((temp = br.readLine()) != null){  
                ret += temp;  
            }     
            br.close();  
            isr.close();
            conn.disconnect();
            //System.out.println(ret);
            jsonRet = new JSONObject(ret);

        } catch(java.net.SocketTimeoutException e) {
            //e.printStackTrace();
            jsonRet = new JSONObject("{\"ret_code\":-1,\"err_msg\":\"call restful timeout\"}");
        } catch(Exception e) {
            //e.printStackTrace();
            jsonRet = new JSONObject("{\"ret_code\":-1,\"err_msg\":\"call restful error\"}");
        }
        return jsonRet;
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

(完)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值