写在前面:
1、为什么不直接new RestTemplate?
因为底层用的是jdk自带的http处理方式,不适合大批量调用http请求使用
2、为什么使用apache的构建器?
因为简单粗暴,使用方式比较直接,当然,也可以手写一个
3、对于spring cloud项目来说,替换一个具有连接池功能的RestTemplate可以提升feign的性能,具体原因参考第一点
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
private static final Logger logger = LoggerFactory.getLogger(RestTemplateConfig.class);
@Bean
public RestTemplate restTemplate(){
int defaultMaxPerRoute = 200;
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
//设置整个连接池最大连接数
connectionManager.setMaxTotal(2 * defaultMaxPerRoute);
//路由是对maxTotal的细分
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
RequestConfig requestConfig = RequestConfig.custom()
//服务器返回数据(response)的时间,超过该时间抛出read timeout
.setSocketTimeout(10000)
//连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
.setConnectTimeout(5000)
//从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
.setConnectionRequestTimeout(1000)
.setCookieSpec(CookieSpecs.STANDARD)
.build();
CloseableHttpClient build = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
// 如果不配置connectionManager,则默认使用System.getProperty获取配置参数
.setConnectionManager(connectionManager)
.build();
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(build));
logger.info("初始化 RestTemplate,bean name :{}","restTemplate");
return restTemplate;
}
}
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>