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

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
        }
    }

}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/114099.html

(0)
上一篇 2021年8月27日
下一篇 2021年8月27日

相关推荐

发表回复

登录后才能评论