Spring Boot: How to set RestTemplate read timeout
Using the class RestTemplateBuilder it is very easy to configure the RestTemplate you need.
Here is a snippet that shows you how to configure the read timeout on a RestTemplate instance.
NB: you can set timeouts in java.time.Duration (instead of int) since Spring Boot 2.1
@Component
public class MyRestClient {
@Value("${service.client.timeout.read}")
private Duration readTimeout;
private RestTemplate restTemplate;
public MyRestClient(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.setReadTimeout(readTimeout)
.build();
}
// Code that actually uses RestTemplate...
}
Then you just have to set the value of the property "service.client.timeout.read" (instead of hardcoding it)
service.client.timeout.read=5s