@Value("${remote.maxTotalConnect:400}")
private int maxTotalConnect;
/* 单个主机的最大连接数 */
@Value("${remote.maxConnectPerRoute:200}")
private int maxConnectPerRoute;
/* 连接超时默认2s */
@Value("${remote.connectTimeout:10000}")
private int connectTimeout;
/* 读取超时默认30s */
@Value("${remote.readTimeout:180000}")
private int readTimeout;
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(this.createFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
// 重新设置StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//加入FastJson转换器
converterList.add(new FastJsonHttpMessageConverter());
return restTemplate;
}
private ClientHttpRequestFactory createFactory() {
if (this.maxTotalConnect <= 0) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
.setMaxConnPerRoute(this.maxConnectPerRoute).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
httpClient);
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
restTemplate中文乱码问题
最新推荐文章于 2024-06-30 00:15:00 发布
该代码段展示了如何使用Spring的@Value注解从配置中读取远程服务的最大连接总数、每个路由的最大连接数、连接超时和读取超时。接着,它创建了一个RestTemplate实例,并定制了其HttpMessageConverter,确保StringHttpMessageConverter使用UTF-8编码并添加了FastJsonHttpMessageConverter来支持FastJson序列化。
摘要由CSDN通过智能技术生成