-1

我正在使用 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();
        }
    });
}

但是多个请求的持续时间无法正常进行。有什么建议吗?

4

1 回答 1

0

如果您不等待所有响应都到达,则无法衡量它们全部到达所需的时间。

FutureCallback您需要为(至少)已收到回复的记录提供非虚拟实现。然后你需要等待回复。

当你这样做时,你还需要处理一些请求可能在服务器端被丢弃的可能性。

于 2019-07-09T08:00:29.363 回答