简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM