说明
RestTemplate是Spring提供的用于访问Rest服务的客户端,可以通过ClientHttpRequestFactory创建。默认采用的是SimpleClientHttpRequestFactory,底层是HttpURLConnection(java.net包提供的方式),不具备连接池的功能,默认超时为-1。可以引入httpClient连接池
使用
- 添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 版本号可能会不同,根据实际情况选择 -->
</dependency>
- 配置
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
return new RestTemplate(factory);
}
private CloseableHttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(50);
connectionManager.setDefaultMaxPerRoute(50);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}
}