Search code examples
javaspringconnection-poolingresttemplate

RestTemplate. How to increase max tcp connections?


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?


Solution

  • 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.