HttpClient4.5 使用http连接池发送http请求深度示例

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

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

public class PoolTest {
    private static void config(HttpRequestBase httpRequestBase) {
        httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
        httpRequestBase.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        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");
        httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
        
        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000)
                .setConnectTimeout(3000)
                .setSocketTimeout(3000)
                .build();
        httpRequestBase.setConfig(requestConfig);        
    }
    public static void main(String[] args) {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        // 将最大连接数增加到200
        cm.setMaxTotal(200);
        // 将每个路由基础的连接增加到20
        cm.setDefaultMaxPerRoute(20);
        // 将目标主机的最大连接数增加到50
        HttpHost localhost = new HttpHost("http://blog.csdn.net/gaolu",80);
        cm.setMaxPerRoute(new HttpRoute(localhost), 50);
        
        //请求重试处理
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception,int executionCount, HttpContext context) {
                if (executionCount >= 5) {// 如果已经重试了5次,就放弃                    
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试                    
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常                    
                    return false;
                }                
                if (exception instanceof InterruptedIOException) {// 超时                    
                    return false;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达                    
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝                    
                    return false;
                }
                if (exception instanceof SSLException) {// ssl握手异常                    
                    return false;
                }
                
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的,就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {                    
                    return true;
                }
                return false;
            }
        };  
        
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setRetryHandler(httpRequestRetryHandler)
                .build();
        // URL列表数组
        String[] urisToGet = {         
                "http://blog.csdn.net/gaolu/article/details/48466059",
                "http://blog.csdn.net/gaolu/article/details/48243103",
                "http://blog.csdn.net/gaolu/article/details/47656987",
                "http://blog.csdn.net/gaolu/article/details/47055029",
                
                "http://blog.csdn.net/gaolu/article/details/46400883",
                "http://blog.csdn.net/gaolu/article/details/46359127",
                "http://blog.csdn.net/gaolu/article/details/46224821",
                "http://blog.csdn.net/gaolu/article/details/45305769",
                
                "http://blog.csdn.net/gaolu/article/details/43701763",
                "http://blog.csdn.net/gaolu/article/details/43195449",
                "http://blog.csdn.net/gaolu/article/details/42915521",
                "http://blog.csdn.net/gaolu/article/details/41802319",
                
                "http://blog.csdn.net/gaolu/article/details/41045233",
                "http://blog.csdn.net/gaolu/article/details/40395425",
                "http://blog.csdn.net/gaolu/article/details/40047065",
                "http://blog.csdn.net/gaolu/article/details/39891877",
                
                "http://blog.csdn.net/gaolu/article/details/39499073",
                "http://blog.csdn.net/gaolu/article/details/39314327",
                "http://blog.csdn.net/gaolu/article/details/38820809",
                "http://blog.csdn.net/gaolu/article/details/38439375",
        };
        
        long start = System.currentTimeMillis();        
        try {
            int pagecount = urisToGet.length;
            ExecutorService executors = Executors.newFixedThreadPool(pagecount);
            CountDownLatch countDownLatch = new CountDownLatch(pagecount);         
            for(int i = 0; i< pagecount;i++){
                HttpGet httpget = new HttpGet(urisToGet[i]);
                config(httpget);
                //启动线程抓取
                executors.execute(new GetRunnable(httpClient,httpget,countDownLatch));
            }
            countDownLatch.await();
            executors.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("线程" + Thread.currentThread().getName() + "," + System.currentTimeMillis() + ", 所有线程已完成,开始进入下一步!");
        }        
        
        long end = System.currentTimeMillis();
        System.out.println("consume -> " + (end - start));
    }
    
    static class GetRunnable implements Runnable {
        private CountDownLatch countDownLatch;
        private final CloseableHttpClient httpClient;
        private final HttpGet httpget;
        
        public GetRunnable(CloseableHttpClient httpClient, HttpGet httpget, CountDownLatch countDownLatch){
            this.httpClient = httpClient;
            this.httpget = httpget;
            
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            CloseableHttpResponse response = null;
            try {
                response = httpClient.execute(httpget,HttpClientContext.create());
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity, "utf-8")) ;
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
                
                try {
                    if(response != null)
                        response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }    
}

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

时间: 2024-07-29 03:51:28

HttpClient4.5 使用http连接池发送http请求深度示例的相关文章

基于线程池和连接池的Http请求

背景:最新项目需求调用http接口,所以打算使用最新的httpClient客户端写一个工具类,写好了以后在实际应用过程中遇到了一些问题,因为数据量还算 大,每次处理大概要处理600-700次请求,平均算下来大概需要20分钟,这个速度虽然是跑在定时任务中的,但是也是不能忍受的,所以有了这个博客. 1.首先想到的解决办法就是多线程发请求了,但是这个有坑,最后会在结果处说明. 2.代码方面如下 ExecutorService executor = Executors.newFixedThreadPoo

使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比

使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比 在项目中需要使用http调用接口,实现了两套发送http请求的方法,一个是使用apache的httpclient提供的http链接池来发送http请求,另一个是使用java原生的HttpURLConnection来发送http请求,并对两者性能进行了对比. 使用httpclient中的链接池发送http请求 使用最新的4.5.2版httpclient进行实现.在maven中引入 <

php连接池 php–cp

原文地址:http://blog.sina.com.cn/s/blog_9eaa0f400102v9fd.html 数据库连接池php-cp介绍时间 2015-01-23 11:53:05 数据库连接池 php-cpphp-cp(php-connect-pool)是用php扩展写的一个数据库连接池. 我们知道php开发速度快,适合创业快速迭代,但当流量大了之后,php大量的短连接给db层造成多余的消耗,而php处理请求过程中连接会一直持有再加上进程之间不能共享tcp连接会导致撑高mysql的连接

《java数据源—连接池》

<java数据源-连接池>1.数据源的分类:直接数据源.连接池数据源.2.连接池.数据源.JNDI a.数据源:Java中的数据源就是连接到数据库的一条路径,数据源中并无真正的数据,它仅仅记录的是你连接到哪个数据库,以及如何连接. b.连接池:简单的说就是保存所有的数据库连接的地方,在系统初始化时,将数据库连接对象存储到内存里,当用户需要访问数据库的时候,并不是建立一个新的连接,而是从连接池中 取出一个已经建立好的空闲连接对象.而连接池负责分配.管理.释放数据库连接对象.注意的是:连接池是由容

利用HttpURLConnecion通过Nginx向代理邮件服务器发送POST请求

第一步:获取邮件各种参数,通过URLencode和Base64编码之后发送请求参数. 请求参数中,有邮件附件这样的大件,如何当做请求发送呢? 首先,将邮件内容转为字节数组,转为字节数组之后可以当做二进制操作了,保持了附件最原始的面貌,不会被任何其他因素影响. byte[] att= attachment.getContent(); //附件内容 //利用Base64进行加密传输,虽然加密的不够 Base64 base64 = new Base64(); //org.apache.commons.

Http请求连接池 - HttpClient 的 PoolingHttpClientConnectionManager

两个主机建立连接的过程是非常复杂的一个过程,涉及到多个数据包的交换,而且也非常耗时间.Http连接须要的三次握手开销非常大,这一开销对于比較小的http消息来说更大.但是假设我们直接使用已经建立好的http连接.这样花费就比較小.吞吐率更大. 传统的HttpURLConnection并不支持连接池.假设要实现连接池的机制,还须要自己来管理连接对象.对于网络请求这种底层相对复杂的操作.个人以为假设有可用的其它方案,也没有必要自己去管理连接对象. 除了HttpURLConnection,大家肯定还知

HttpClient 4.3连接池参数配置及源码解读

目前所在公司使用HttpClient 4.3.3版本发送Rest请求,调用接口.最近出现了调用查询接口服务慢的生产问题,在排查整个调用链可能存在的问题时(从客户端发起Http请求->ESB->服务端处理请求,查询数据并返回),发现原本的HttpClient连接池中的一些参数配置可能存在问题,如defaultMaxPerRoute.一些timeout时间的设置等,虽不能确定是由于此连接池导致接口查询慢,但确实存在可优化的地方,故花时间做一些研究.本文主要涉及HttpClient连接池.请求的参数

HttpClient连接池的连接保持、超时和失效机制

HTTP是一种无连接的事务协议,底层使用的还是TCP,连接池复用的就是TCP连接,目的就是在一个TCP连接上进行多次的HTTP请求从而提高性能.每次HTTP请求结束的时候,HttpClient会判断连接是否可以保持,如果可以则交给连接管理器进行管理以备下次重用,否则直接关闭连接.这里涉及到三个问题: 1.如何判断连接是否可以保持? 要想保持连接,首先客户端需要告诉服务器希望保持长连接,这就是所谓的Keep-Alive模式(又称持久连接,连接重用),HTTP1.0中默认是关闭的,需要在HTTP头加

JAVAWEB开发之事务详解(mysql与JDBC下使用方法、事务的特性、锁机制)和连接池的详细使用(dbcp以d3p0)

事务简介 事务的概念:事务指逻辑上的一组操作,组成这组操作的各个单元,要么全部成功,要么全部不成功 在开发中,有事务的存在,可以保证数据的完整性. 注意:数据库默认事务是自动提交的,也就是发一条SQL 就执行一条.如果想多条SQL语句放在一个事务中执行,需要添加事务有关的语句. 如何开启事务? 事务的操作方式: 创建表: create table account( id int primary key auto_increment, name varchar(20), money double