What is the right way to use HttpClientConnectionManager with CloseableHttpClient in Apache?

Viewed 400

Context

I have an instance of org.apache.hc.client5.http.impl.classic.CloseableHttpClient and a singleton instance of org.apache.hc.client5.http.io.HttpClientConnectionManager to communicate with some remote API.

I have created a singleton pool of HTTP connections to create an instance of the HTTP client.

What is the right way to use HttpClientConnectionManager?

Should I really use try-with-resource (or old-style try-finally) to work with CloseableHttpClient?

If I close the HTTP client, a connection will be closed also from this pool. And then I can't use this pool to communicate with a remote API.

Of course, I've read the documentation https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html

Maybe something I missed. Could anyone explain me?

1 Answers

You should also be using CloseableHttpClient as a singleton (on a per distinct service basis).

If you want to continue creating short lived instances of CloseableHttpClient with the same HttpClientConnectionManager please make sure to mark it as shared when creating CloseableHttpClient instances with HttpClientBuilder.

Related