基于 java config 的配置方式
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
RestTemplate restTemplate = new RestTemplate(requestFactory);
// 设置错误处理器
restTemplate.setErrorHandler(null);
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(1);
// 设置拦截器 , 该连接器可在 Request & Response 时作用
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory requestFactory() {
// 创建一个 ClientHttpRequestFactory , spring 有多种实现
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(3000);
requestFactory.setReadTimeout(3000);
return requestFactory;
}
}