《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
}
}
}
最後更新:2017-05-19 13:32:09
上一篇:
《HttpClient官方文檔》4.1-4.3 HTTP驗證
下一篇:
D-News | 中國發布首個VR標準,穀歌為數據中心研發SDN新架構Espresso
簡析Go與其他語言不同的類型
Error 1115 Unknow character set ‘gbk’
7月18日雲棲精選夜讀:Bridge to the digital world —— AR算法技術分享
js中window.showModalDialog各瀏覽器居中和傳參實例兼以及一些兼容性問題
PLM調研第三天
Consul+Prometheus係統監控之注冊發現
《數據驅動安全:數據安全分析、可視化和儀表盤》一1.2.5 可視化
ubuntu下編寫開機自啟守護進程,並記錄進程信息到日誌文件
Java類加載器學習2——自定義類加載器和父類委托機製帶來的問題
馬雲爸爸不惜花重金請你來嗨的音樂節,【竇靖童】領銜大咖陣容全曝光!