sardo sardo - 1 year ago 304
reST (reStructuredText) Question

Spring RestTemplate timeout

I would like to set the connection timeouts for a rest service used by my web application. I'm using Spring's RestTemplate to talk to my service. I've done some research and I've found and used the xml below (in my application xml) which I believe is meant to set the timeout. I'm using Spring 3.0.

I've also seen the same problem here Timeout configuration for spring webservices with RestTemplate but the solutions don't seem that clean, I'd prefer to set the timeout values via Spring config

<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">

<bean class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<property name="readTimeout" value="${restURL.connectionTimeout}" />

It seems whatever I set the readTimeout to be I get the following:

Network cable disconnected:
Waits about 20 seconds and reports following exception:

org.springframework.web.client.ResourceAccessExcep tion: I/O error: No route to host: connect; nested exception is No route to host: connect

Url incorrect so 404 returned by rest service:
Waits about 10 seconds and reports following exception:

org.springframework.web.client.HttpClientErrorException: 404 Not Found

My requirements require shorter timeouts so I need to be able to change these. Any ideas as to what I'm doing wrong?

Many thanks.

Answer Source

I finally got this working.

I think the fact that our project had two different versions of the commons-httpclient jar wasn't helping. Once I sorted that out I found you can do two things...

In code you can put the following:

HttpComponentsClientHttpRequestFactory rf =
    (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setReadTimeout(1 * 1000);
rf.setConnectTimeout(1 * 1000);

The first time this code is called it will set the timeout for the HttpComponentsClientHttpRequestFactory class used by the RestTemplate. Therefore, all subsequent calls made by RestTemplate will use the timeout settings defined above.

Or the better option is to do this:

<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <property name="readTimeout" value="${application.urlReadTimeout}" />
            <property name="connectTimeout" value="${application.urlConnectionTimeout}" />

Where I use the RestOperations interface in my code and get the timeout values from a properties file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download