英文:
RestTemplate. How to increase max tcp connections?
问题
我有一个 RestTemplate:
@Bean(name = "restTemplateBean")
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.interceptors(new HttpRequestInterceptor())
.uriTemplateHandler(new DefaultUriBuilderFactory((host + ":" + port)))
.build();
}
当我调用 RestTemplate 多次(例如进行 POST 请求),它最多会创建 5 到 10 个 TCP 连接。我该如何增加 RestTemplate 创建的最大连接数呢?
英文:
I have RestTemplate:
@Bean(name = "restTemplateBean")
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.interceptors(new HttpRequestInterceptor())
.uriTemplateHandler(new DefaultUriBuilderFactory((host + ":" + port)))
.build();
}
When I call a large number of times the RestTemplate (post requests, for example) it creates a maximum of 5 ~ 10 TCP connections. How could I increase the maximum number of connections created by RestTemplate?
答案1
得分: 7
你可以利用 Apache 的 HttpClient 进行连接池管理。使用 HttpClientBuilder 并增加 maxConnPerRoute 和 maxConnTotal 来达到所需的性能:
@Bean
public HttpClientBuilder httpClientBuilder() {
return HttpClients.custom()
.setMaxConnPerRoute(PER_ROUTE)
.setMaxConnTotal(TOTAL);
}
@Bean
public RestTemplate restTemplate(HttpClientBuilder httpClientBuilder) {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClientBuilder.build());
return new RestTemplate(requestFactory);
}
其中,maxConnPerRoute 限制了对单个 IP:port 可以建立的连接数,而 maxTotal 则限制了可以打开的总连接数。
英文:
You can take advantage of connection pooling with Apache's HttpClient. Use HttpClientBuilder and increasing maxConnPerRoute and maxConnTotal to reach the performance you're looking for:
@Bean
public HttpClientBuilder httpClientBuilder() {
return HttpClients.custom()
.setMaxConnPerRoute(PER_ROUTE)
.setMaxConnTotal(TOTAL);
}
@Bean
public RestTemplate restTemplate(HttpClientBuilder httpClientBuilder) {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClientBuilder.build());
return new RestTemplate(requestFactory);
}
maxConnPerRoute limits how many connections can be made to a single IP:port, and maxTotal limits the number of total connections that can be opened.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论