Blog Archives

Setting timeout for REST and SOAP webservices in Spring


I got in a situation where one of the external providers were missing their SLA and instead of their agreed 3 sec (hypothetical) for response, webservice was taking ~1 minute.
In this situation, the component was taking a lot of time to load -slowing down the whole page response. Following are the way to set the timeout parameter:

  • Setting JVM parameter (This will work ONLY for RESTfull services -Basically services dependent on JDK HTTP client)
    1. -Dsun.net.client.defaultConnectTimeout=1000 (Time to establish connection in millisec)
    2. -Dsun.net.client.defaultReadTimeout=1000 (Time to read content in millisec)

This works because Spring template by default uses HTTPClient from JDK, if the factory class has been overridden to non JDK class it will fail

  • Injecting the parameters for REST template
  • 	<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    		<constructor-arg>
        		<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
        			<property name="readTimeout" value="100" />
        			<property name="connectTimeout" value="100"/>
       		 	</bean>
    		</constructor-arg>
    	</bean>   
    

    Be sure not to use the depricated class “org.springframework.http.client.CommonsClientHttpRequestFactory”, otherwise it throws an error while setting connectTimeout

  • Injecting the parameters for SOAP Service
  •         <property name="messageSender">
                <bean
                    class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
                         <property name="connectionTimeout" value="10" />
                  <property name="readTimeout" value="100" />
                </bean>
            </property>
    
    Advertisements