HTTP 连接池
* 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(50); // 最大连接数
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(20); // 每个路由的默认最大连接数
CloseableHttpClient closeableHttpClient = HttpClients
.custom()
.setConnectionManager(poolingHttpClientConnectionManager)
.build();
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(closeableHttpClient);
httpComponentsClientHttpRequestFactory.setConnectTimeout(5000); // 连接超时时间
httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(5000); // 请求超时时间
return new RestTemplate(httpComponentsClientHttpRequestFactory);
}
}
// OKHttp Spring 3+ 已废弃
// Apache Client Spring 3+ 使用 Apache Client5