spring Springs RestTemplate 默认连接池
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44188847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Springs RestTemplate default connection pool
提问by Sam
Just wondering if RestTemplate out of the box uses connection pooling or does it simply establish a new connection each time ?
只是想知道 RestTemplate 是开箱即用的使用连接池还是每次都简单地建立一个新连接?
采纳答案by ootero
I believe RestTemplatedoesn't use a connection pool to send requests, it uses a SimpleClientHttpRequestFactorythat wraps a standard JDK's HttpURLConnectionopening and closing the connection.
我相信RestTemplate不使用连接池来发送请求,它使用一个SimpleClientHttpRequestFactory包装标准JDK的HttpURLConnection打开和关闭连接。
Indeed you can configure RestTemplateto use a pooled implementation such as HttpComponentsClientHttpRequestFactorybut most-likely you might also need to configure some settings to prevent requests from timing out.
实际上,您可以配置RestTemplate为使用池化实现,HttpComponentsClientHttpRequestFactory但很可能您还需要配置一些设置以防止请求超时。
I have blogged about this issue at Troubleshooting Spring's RestTemplate Requests Timeout
我在对 Spring 的 RestTemplate 请求超时进行故障排除中写了关于这个问题的博客
回答by Praneeth Ramesh
By default RestTemplate creates new Httpconnection every time and closes the connection once done.
默认情况下,RestTemplate 每次都会创建新的 Httpconnection,并在完成后关闭连接。
If you need to have a connection pooling under rest template then you may use different implementation of the ClientHttpRequestFactory that pools the connections.
如果您需要在休息模板下有一个连接池,那么您可以使用连接连接池的 ClientHttpRequestFactory 的不同实现。
new RestTemplate(new HttpComponentsClientHttpRequestFactory())
回答by Volodymyr Kret
Yes, Spring RestTemplateBuilder uses apache httpclient for pooling (usage). RestTemplateBuilder creates HttpComponentsClientHttpRequestFactory and uses HttpClientBuilder. HttpClientBuilder is the most interesting (source):
是的,Spring RestTemplateBuilder 使用 apache httpclient 进行池化(使用)。RestTemplateBuilder 创建 HttpComponentsClientHttpRequestFactory 并使用 HttpClientBuilder。HttpClientBuilder 是最有趣的(来源):
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:
因此,默认情况下,每个路由(主机)的池大小等于 5。总池大小 = 10。要检查连接池日志记录,请按如下方式设置日志记录级别:
org.apache.http.impl.conn.PoolingHttpClientConnectionManager=TRACE
回答by Kishan B
We can use okhttpclient underneath spring's rest template to use connection pooling. A detailed blog on this below
我们可以在 spring 的 rest 模板下使用 okhttpclient 来使用连接池。下面有一个详细的博客
https://www.bytesville.com/changing-httpclient-in-spring-resttemplate/
https://www.bytesville.com/changed-httpclient-in-spring-resttemplate/

