RestTemplate的优化 Posted on 2019-06-15 | Edited on 2022-09-21 | In java , spring 用RestTemplate上传图片发现请求经常超时,修改了下ClientHttpRequestFactory明显有所改善。mark下,具体见代码 123456789101112131415161718192021222324252627282930313233343536373839404142434445@Configurationpublic 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; }}