Reponse time in CloseableHttpAsyncClient

1k Views Asked by At

I am using CloseableHttpAsyncClient API of apache to hit multiple requests without caring for response.

My code :-

//Setting HTTP client :-

 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();
        }
    });
}

But duration in multiple request in not coming properly. Any suggestion ?

1

There are 1 best solutions below

0
On

If you don't wait for all of the responses to arrive, you cannot measure how long it takes for them to all arrive.

You need to provide a non-dummy implementation for FutureCallback that (at least) records that a reply has been received. Then you need to wait for the replies.

When you do that, you will also need to deal with the possibility that some requests may be dropped at the server end.