RestTemplate。如何增加最大TCP连接?

huangapple go评论79阅读模式
英文:

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 并增加 maxConnPerRoutemaxConnTotal 来达到所需的性能:

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

huangapple
  • 本文由 发表于 2020年9月1日 18:30:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63685926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定