閱讀911 返回首頁    go 阿裏雲 go 技術社區[雲棲]


《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 = {
    "https://www.domain1.com/",
    "https://www.domain2.com/",
    "https://www.domain3.com/",
    "https://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

最後更新:2017-05-19 13:32:09

  上一篇:go  《HttpClient官方文檔》4.1-4.3 HTTP驗證
  下一篇:go  D-News | 中國發布首個VR標準,穀歌為數據中心研發SDN新架構Espresso