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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.