简体   繁体   中英

Setting timeouts in Spring Rest Template

Application is using Spring rest template to call a webservice and i am using
restTemplate.exchage(url) to call the webservice. Currently we are not passing any timeout value for this webservice call, How can i set a timeout value for Spring Rest template.

You can use code similar to following for setting connection timeout:

RestTemplate restTemplate = new RestTemplate();
((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setConnectTimeout(2000);

If your wish to set read timeout, you can have code similar to following:

((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setReadTimeout(2000);

The time is given in milliseconds here. For more info, you can visit the documentation page .

RestTemplateBuilder introduced since Spring 1.4 could be used to set read and connect timeout settings for RestTemplate object. Here is sample code -

final RestTemplate restTemplate =
    new RestTemplateBuilder()
        .setConnectTimeout(Duration.ofMillis(connectTimeoutMillis))
        .setReadTimeout(Duration.ofMillis(readTimeoutMillis))
        .build();

I use this approach based on these threads

int DEFAULT_TIMEOUT = 5000;
RequestConfig requestConfig = RequestConfig.custom()
 .setConnectTimeout(DEFAULT_TIMEOUT)
 .setConnectionRequestTimeout(DEFAULT_TIMEOUT)
 .setSocketTimeout(DEFAULT_TIMEOUT)
 .build();

CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .build();

Spring RestTemplate Connection Timeout is not working

Java : HttpClient 4.1.2 : ConnectionTimeout, SocketTimeout values set are not effective

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM