Spring Boot Version: 2.1.18.RELEASE, 2.3.12.RELEASE, 2.5.2
I use okhttp
as the RequestFactory
of RestTemplate
, so i create a RestTemplateCustomizer
bean.
@Bean
public RestTemplateCustomizer okHttpRequestFactoryRestTemplateCustomizer() {
return restTemplate ->
restTemplate.setRequestFactory(new OkHttp3ClientHttpRequestFactory(new OkHttpClient.Builder().build()));
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofSeconds(3))
.build();
}
But the setConnectTimeout not working, i debugged the build process, i found that setting the timeout period is in the buildRequestFactory()
phase, while the custom setting RequestFactory is executed at the end, so it did not work.
public <T extends RestTemplate> T configure(T restTemplate) {
ClientHttpRequestFactory requestFactory = buildRequestFactory();
// ...
if (!CollectionUtils.isEmpty(this.customizers)) {
for (RestTemplateCustomizer customizer : this.customizers) {
customizer.customize(restTemplate);
}
}
return restTemplate;
}
Comment From: wilkinsona
This is to be expected. As the builder’s javadoc notes, the builder configures the connect timeout on the underlying request factory and customizers are applied after the builder configuration has been applied. You are replacing the request factory in a customizer so you have overridden the builder’s configuration.
Rather than using a RestTemplateCustomizer
to change the request factory, I would recommend defining your own RestTemplateBuilder
bean with a customized request factory instead.