Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate - How to set connect timeout and read time out

Tags:

spring-mvc

I am using spring 3.0.5 version of RestTemplate Can any one help me .how to set connecttimeout and readTimeout values for each request

but in latest versions there is a solution with HttpComponentsClientHttpRequestFactory class .but i need with spring.web.3.0.5 version

like image 235
hari Avatar asked Apr 14 '15 06:04

hari


3 Answers

private void setTimeout(RestTemplate restTemplate, int timeout) {
    //Explicitly setting ClientHttpRequestFactory instance to     
    //SimpleClientHttpRequestFactory instance to leverage 
    //set*Timeout methods
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(timeout);
    rf.setConnectTimeout(timeout);
}
like image 69
Balaji Katika Avatar answered May 24 '23 23:05

Balaji Katika


I am using Spring 5.2 and got clean way of setting read and connect timeout settings for RestTemplate object:

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
            .setConnectTimeout(Duration.ofMillis(connectTimeoutMillis))
            .setReadTimeout(Duration.ofMillis(readTimeoutMillis))
            .build();
    }
like image 43
realPK Avatar answered May 25 '23 00:05

realPK


@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {

        var factory = new SimpleClientHttpRequestFactory();

        factory.setConnectTimeout(3000);
        factory.setReadTimeout(3000);

        return new RestTemplate(factory);
    }
}
like image 44
Prasad Avatar answered May 25 '23 00:05

Prasad