Just wondering if RestTemplate out of the box uses connection pooling or does it simply establish a new connection each time ?
Yes, Spring RestTemplateBuilder uses apache httpclient for pooling (usage). RestTemplateBuilder creates HttpComponentsClientHttpRequestFactory and uses HttpClientBuilder. HttpClientBuilder is the most interesting (source):
s = System.getProperty("http.maxConnections", "5");
int max = Integer.parseInt(s);
poolingmgr.setDefaultMaxPerRoute(max);
poolingmgr.setMaxTotal(2 * max);
So, by default, pool size per route (host) is equal to 5. Total pool size = 10. To check connection pool logging set logging level as follows:
org.apache.http.impl.conn.PoolingHttpClientConnectionManager=TRACE
We can use okhttpclient underneath spring's rest template to use connection pooling. A detailed blog on this below
https://www.bytesville.com/changing-httpclient-in-spring-resttemplate/
I believe RestTemplate
doesn’t use a connection pool to send requests, it uses a SimpleClientHttpRequestFactory
that wraps a standard JDK
’s HttpURLConnection
opening and closing the connection.
Indeed you can configure RestTemplate
to use a pooled implementation such as HttpComponentsClientHttpRequestFactory
but most-likely you might also need to configure some settings to prevent requests from timing out.
I have blogged about this issue at Troubleshooting Spring's RestTemplate Requests Timeout
By default RestTemplate creates new Httpconnection every time and closes the connection once done.
If you need to have a connection pooling under rest template then you may use different implementation of the ClientHttpRequestFactory that pools the connections.
new RestTemplate(new HttpComponentsClientHttpRequestFactory())