Springs RestTemplate default connection pool

一笑奈何 提交于 2019-12-02 20:45:51

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

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!