Tom
Tom

Reputation: 3166

Setting a read timeout for RestTemplate

I'm using Spring RestTemplate to make simple POST requests from my application to varying REST endpoints. Currently I set the readTimout in the Spring config file as shown:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <constructor-arg>
        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <property name="readTimeout" value="10000" />
            <property name="connectTimeout" value="10000"/>
        </bean>
    </constructor-arg>
</bean>

Recently I was tasked with the requirement for the readTimout to be set dynamically on per request basis

I'm thinking I would have to inject a new RequestFactory into the restTemplate with the new timeout value each time I make a POST request but is this an acceptable way to accomplish this? Is there a better way?

Upvotes: 1

Views: 924

Answers (1)

Tom
Tom

Reputation: 3166

Instead of injecting a new RequestFactory into the restTemplate each time I found that I could just set the read timeout explicitly on the HttpComponentsClientHttpRequestFactory object.

((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setReadTimeout(timeout)

Upvotes: 1

Related Questions