《HttpClient官方文档》2.4 多线程请求执行

本文介绍如何利用HttpClient和PoolingClientConnectionManager实现多线程并发请求。通过创建线程池和为每个URI启动一个线程的方式,实现了高效的HTTP请求处理。需要注意的是,每个线程应维护自己的HttpContext实例。

2.4.多线程请求执行

当HttpClient拥有类似PoolingClientConnectionManage类这样的池连接管理器,它就能够使用多线程来并发执行多个请求。

PoolingClientConnectionManager类将根据其配置分配连接。如果给定路由的所有连接都已租用,则会阻塞对连接的请求,直到有连接释放回到连接池。可以通过将“http.conn-manager.timeout”设置为正值来确保连接管理器在连接请求操作中不会无限期地阻塞。如果连接请求不能在给定的期限内提供服务,会抛出ConnectionPoolTimeoutException异常。

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionManager(cm)
        .build();

// URIs to perform GETs on
String[] urisToGet = {
    "http://www.domain1.com/",
    "http://www.domain2.com/",
    "http://www.domain3.com/",
    "http://www.domain4.com/"
};

// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
    HttpGet httpget = new HttpGet(urisToGet[i]);
    threads[i] = new GetThread(httpClient, httpget);
}

// start the threads
for (int j = 0; j < threads.length; j++) {
    threads[j].start();
}

// join the threads
for (int j = 0; j < threads.length; j++) {
    threads[j].join();
}

HttpClient接口的实例是线程安全的,可以在多个执行线程之间共享,强烈建议每个线程维护自己的专用HttpContext接口实例。

static class GetThread extends Thread {

    private final CloseableHttpClient httpClient;
    private final HttpContext context;
    private final HttpGet httpget;

    public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {
        this.httpClient = httpClient;
        this.context = HttpClientContext.create();
        this.httpget = httpget;
    }

    @Override
    public void run() {
        try {
            CloseableHttpResponse response = httpClient.execute(
                    httpget, context);
            try {
                HttpEntity entity = response.getEntity();
            } finally {
                response.close();
            }
        } catch (ClientProtocolException ex) {
            // Handle protocol errors
        } catch (IOException ex) {
            // Handle I/O errors
        }
    }

}

 转载自 并发编程网 - ifeve.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值