Search code examples
springspring-bootspring-rest

Spring rest template readTimeOut


I'm trying to understand the readTimeout available on restTemplate, what is it exactly ?

Is it the the total amount of time the request can take before we get the timeout exception ?


Solution

  • 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.setReadTimeout(500);
    
    RestTemplate restTemplate = new RestTemplate(clientRequestFactory);
    

    Given a readTimeout of X millis, any request made through that RestTemplate instance which takes longer than X millis will result in a ResourceAccessException, wrapping a java.net.SocketTimeoutException with the exception message: "Read timed out".

    The timeout is actually implemented by the socket connector inside the HttpClient instance which is wrapped by the RestTemplate so the clock starts when the request first hits that socket and stops when whichever of these comes first: the request completes or the readTimeout is reached.

    In effect this means that any request which takes longer than the configured readTimeout will fail with a timeout exception.