Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sping's restTemplate with a timeout, how do I detect a timeout?

I've initialized my restTemplate as follows:

HttpClient httpClient = HttpClientBuilder.create().build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(1000);
requestFactory.setReadTimeout(1000);
restTemplate = new RestTemplate(requestFactory);

and I'm calling it like so:

restTemplate.getForEntity(someString, String.class, SomeHashmapWithURLParameters)

How do I handle both timeouts? I assume an exception will be thrown? If so which specific exception can I catch, in order to specifically handle just timeouts. I'm handeling other exceptions in different ways.

like image 601
linuxdan Avatar asked Mar 05 '16 00:03

linuxdan


People also ask

How do you read a RestTemplate timeout?

You can define a read timeout on a RestTemplate as follows: HttpComponentsClientHttpRequestFactory clientRequestFactory = new HttpComponentsClientHttpRequestFactory(); // set the read timeout, this value is in milliseconds clientRequestFactory.

How do I set timeout on RestTemplate?

RestTemplate default timeoutprivate int connectTimeout = - 1 ; private int readTimeout = - 1 ; By default, resttemplate uses timeout property from JDK installed on the machine which is always infinite in not overridden. To override the default JVM timeout, we can pass these properties during JVM start.

What is the default read timeout for RestTemplate?

The default timeout is infinite. By default RestTemplate uses SimpleClientHttpRequestFactory and that in turn uses HttpURLConnection.

How do you implement timeout in REST API?

One way we can implement a request timeout on database calls is to take advantage of Spring's @Transactional annotation. It has a timeout property that we can set. The default value for this property is -1, which is equivalent to not having any timeout at all.


1 Answers

In case of RestTemplate, when the request gets timed out, Spring will throw ResourceAccessException. Underlying exception under that instance will be java.net.SocketTimeoutException with message 'Read timed out'.

like image 90
Darshan Mehta Avatar answered Oct 21 '22 20:10

Darshan Mehta