首页 > 解决方案 > RestTemplate 与自定义 ConnectionPool?

问题描述

我正在使用以下配置来创建一个RestTemplatebean。

@Bean
@Primary
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

    return builder.requestFactory(() -> new BufferingClientHttpRequestFactory(factory))
            .build();
}

问题:默认情况下HttpClient实例化如下:

org.apache.http.impl.client.HttpClientBuilder:

    String s = System.getProperty("http.keepAlive", "true");
    if ("true".equalsIgnoreCase(s)) {
        s = System.getProperty("http.maxConnections", "5");
        int max = Integer.parseInt(s);
        poolingmgr.setDefaultMaxPerRoute(max);
        poolingmgr.setMaxTotal(2 * max);
    }

因此,默认情况下,该 rest 模板上最多有 10 个并发 url 连接。

问题:使用时如何最好地配置最大总数spring-boot?我没有找到任何application.properties将其设置为自定义值的条目。

附带问题:每条路线的属性是什么意思?是一条路线localhost:8080/myfirst,另一条路线是localhost:8080/mysnd什么?还是两者都是同一条路线localhost:8080

标签: javaspringspring-bootresttemplatespring-web

解决方案


对不起,我误解了你的问题。

很简单:application.properties您可以创建自己的配置。例如:

## Connection pool max size to appache http client
myProjectId.http.maxConnections=100

然后在你的 Bean/Service/Something 中你可以通过简单的动作注入它

@Bean
public class HttpClient  {

    @Value( "${myProjectId.http.maxConnections}" )
    private int maxConnections;

    // some code below

}

推荐阅读