Reputation: 8102
How do I create a ConnectionReuseStrategy
that only reuses connections within the same HttpContext.
e.g. When executing a request in a HttpContext, there may be a redirect to an external domain and back that creates a new connection for the external domain, and reuses the first connection to the original domain when it returns.
However once I'm finished with this HttpContext, and I execute the same request in a new HttpContext, it should not reuse the connections even though the domains are the same. I cannot manually close all connections in the HttpClient since there are parallel HttpContext threads running and they should not reuse each others connections.
Upvotes: 1
Views: 2728
Reputation: 27518
You could leverage HttpClient ability to maintain stateful connections [1]
One can either manually manage user identity by setting a user token uniquely identifying a particular user in the execution context
HttpClientContext context = HttpClientContext.create();
context.setUserToken("user 1");
Or use a custom user token handler to do it automatically for all requests.
This code snippet demonstrates how one can use thread id to make HttpClient re-use persistent connections only when created by the same thread.
UserTokenHandler userTokenHandler = new UserTokenHandler() {
@Override
public Object getUserToken(final HttpContext context) {
return Thread.currentThread().getId();
}
};
CloseableHttpClient client = HttpClients.custom()
.setUserTokenHandler(userTokenHandler)
.build();
[1] http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/advanced.html#stateful_conn
Upvotes: 3