[英]Apache HttpClient: first call very slow, following calls very fast
[英]Apache async HttpClient not fast
我是Apache http客戶端的新手,我正試圖從網站獲取狀態代碼。 在Apache http教程中找到以下示例。
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
public class Abc {
static long d2;
public static void main(final String[] args) throws Exception {
d2=System.currentTimeMillis();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(3000)
.setConnectTimeout(3000).build();
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
try {
httpclient.start();
final HttpGet[] requests = new HttpGet[] {
new HttpGet("http://192.168.26.175:8080/examples/eye/abc10000.jsp")
};
final CountDownLatch latch = new CountDownLatch(1);
for (int v=0;v<1000;v++) {
httpclient.execute(requests[0], new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
latch.countDown();
System.out.println(requests[0].getRequestLine() + "->" + response.getStatusLine());
}
public void failed(final Exception ex) {
latch.countDown();
System.out.println(requests[0].getRequestLine() + "->" + ex);
}
public void cancelled() {
latch.countDown();
System.out.println(requests[0].getRequestLine() + " cancelled");
}
});
}
latch.await();
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
long d1=System.currentTimeMillis();
System.out.println(d1-d2);
}
}
它是真的異步還是串行調用。 必須采取哪些措施才能使調用異步且速度更快。
由於請求將在必須進行更改后通過相同的路徑。
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setDefaultRequestConfig(requestConfig)
.setMaxConnPerRoute(1000)
.setMaxConnTotal(1000)
.build();
首先: CloseableHttpAsyncClient
實例非常昂貴。 請不要創建一個新的CloseableHttpAsyncClient
為每一個請求。 就像為每個鏈接點擊創建一個新的瀏覽器進程一樣,完全是浪費而且非常慢。 強烈建議在邏輯組件的整個生命周期中使用相同的CloseableHttpAsyncClient
實例。
幾乎在所有情況下,阻塞客戶端可能比非阻塞(基於NIO)的客戶端快得多(只要並發請求的數量低於1000,例如1000)。 除非您正在構建某種類型的代理,否則阻止HTTP客戶端(如Apache HttpClient)可能會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.