Springs RestTemplate default connection pool

前端 未结 4 1639
轮回少年
轮回少年 2020-12-24 13:12

Just wondering if RestTemplate out of the box uses connection pooling or does it simply establish a new connection each time ?

相关标签:
4条回答
  • 2020-12-24 13:33

    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
    
    0 讨论(0)
  • 2020-12-24 13:39

    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/

    0 讨论(0)
  • 2020-12-24 13:50

    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

    0 讨论(0)
  • 2020-12-24 13:51

    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())
    
    0 讨论(0)
提交回复
热议问题