我正在使用apache的CloseableHttpAsyncClient API来查看多个请求,而无需关心响应。
我的代码: -
//设置HTTP客户端: -
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setConnectTimeout(connectTimeOut)
.setSoTimeout(socketTimeOut)
.build();
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
connManager.setMaxTotal(maxTotalConnection);
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setConnectionManager(connManager)
.setDefaultCredentialsProvider(provider)
.build();
httpclient.start();
//Hit multiple request :-
int totalRequestCount = 1500;
for(int i = 1; i < totalRequestCount : i++) {
final HttpPost postRequest = new HttpPost(url);
StringEntity stringEntity;
try {
stringEntity = new StringEntity(requestString);
stringEntity.setContentType("application/json");
postRequest.setEntity(stringEntity);
} catch (UnsupportedEncodingException e) {
}
long startTime = System.currentTimeMillis();
httpclient.execute(postRequest, new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
long endTime = System.currentTimeMillis();
long duation = endTime - startTime;
}
public void failed(final Exception ex) {
postRequest.releaseConnection();
}
public void cancelled() {
postRequest.releaseConnection();
}
});
}
但多次请求的持续时间未正确。 有什么建议吗?
答案 0 :(得分:0)
如果您不等待所有响应到达,则无法衡量所有响应到达需要多长时间。
您需要为FutureCallback
提供一个非虚拟的实现,该实现(至少)记录已收到回复。然后,您需要等待回复。
这样做时,还需要处理一些请求可能在服务器端被丢弃的可能性。