RestTemplate的优化

用RestTemplate上传图片发现请求经常超时,修改了下ClientHttpRequestFactory明显有所改善。mark下,具体见代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@Configuration
public class RestConfigure {

@Autowired
private HttpLogInterceptor httpLogInterceptor;

@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(clientHttpRequestFactory());
restTemplate.setInterceptors(Collections.singletonList(httpLogInterceptor));
return restTemplate;
}

@Bean
public HttpClientConnectionManager poolingConnectionManager() {
PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
// 连接池最大连接数
poolingConnectionManager.setMaxTotal(Runtime.getRuntime().availableProcessors()*2);
// 每个路由的最大连接数
poolingConnectionManager.setDefaultMaxPerRoute(Runtime.getRuntime().availableProcessors()*2);
return poolingConnectionManager;
}

@Bean
public HttpClientBuilder httpClientBuilder() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//设置HTTP连接管理器
httpClientBuilder.setConnectionManager(poolingConnectionManager());
return httpClientBuilder;
}

@Bean
public ClientHttpRequestFactory clientHttpRequestFactory() {
//比 HttpComponentsClientHttpRequestFactory 性能好上传一个10MB文件从10s-->400ms
OkHttp3ClientHttpRequestFactory clientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory();
// 链接超时,毫秒
clientHttpRequestFactory.setConnectTimeout(1000);
// 读写超时,毫秒
clientHttpRequestFactory.setWriteTimeout(10000);
clientHttpRequestFactory.setReadTimeout(10000);
return clientHttpRequestFactory;
}

}