java 在 Spring Rest 模板中设置超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32983328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:02:01  来源:igfitidea点击:

Setting timeouts in Spring Rest Template

javaspringweb-servicesrest

提问by Sajal Saxena

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.

应用程序使用 Spring rest 模板来调用 webservice,我使用
restTemplate.exchage(url) 来调用 webservice。目前我们没有为此 Web 服务调用传递任何超时值,如何为 Spring Rest 模板设置超时值。

回答by Balwinder Singh

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.

这里的时间以毫秒为单位。有关更多信息,您可以访问文档页面

回答by Alexander Pinzon Fernandez

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();

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

Spring RestTemplate Connection Timeout is not working

Spring RestTemplate 连接超时不起作用

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

Java : HttpClient 4.1.2 : ConnectionTimeout、SocketTimeout 值设置无效

回答by realPK

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

从 Spring 1.4 开始引入的 RestTemplateBuilder 可用于为 RestTemplate 对象设置读取和连接超时设置。这是示例代码 -

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