1. 程式人生 > >《HttpClient官方文件》2.4 多執行緒請求執行

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

}