Correct Way to Implement Http Connection Pooling

What is the best way for pooling httpclient?

If you refer to Apache HTTP client then you may follow the steps below:

  1. Initiate Apache HTTP client only once, since it is thread safe you can safely reuse it. If you use Spring then it should be safe to store it in the Spring Context as a Bean. See following link for the thread-safety.

  2. Despite the fact that HTTP client instance itself is not pooled (since you gonna use single instance of it) what you can do to increase the performance is configuring pooled connection manager on the HTTP client. See following link for the details.
    (search for the 'Pooling connection manager' on that page) . The actual code should be something similar to the snippet bellow :

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("localhost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);

CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();

Hope this helps .

Connection pooling in java using HttpClient

[assuming Java, and Apache's HttpClient]

Use a ThreadSafeClientConnManager. Pass a single global instance to the constructor of every HttpClient instance. I don't think there's any point in pooling the HttpClients themselves.



Related Topics



Leave a reply



Submit