Java 使用带有超时的 sping 的 restTemplate,如何检测超时?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35808577/
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
Using sping's restTemplate with a timeout, how do I detect a timeout?
提问by linuxdan
I've initialized my restTemplate as follows:
我已经初始化了我的 restTemplate 如下:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(1000);
requestFactory.setReadTimeout(1000);
restTemplate = new RestTemplate(requestFactory);
and I'm calling it like so:
我这样称呼它:
restTemplate.getForEntity(someString, String.class, SomeHashmapWithURLParameters)
How do I handle both timeouts? I assume an exception will be thrown? If so which specific exception can I catch, in order to specifically handle just timeouts. I'm handeling other exceptions in different ways.
我如何处理两个超时?我假设会抛出异常?如果是这样,我可以捕获哪个特定异常,以便专门处理超时。我正在以不同的方式处理其他异常。
采纳答案by Darshan Mehta
In case of RestTemplate
, when the request gets timed out, Spring will throw ResourceAccessException. Underlying exception under that instance will be java.net.SocketTimeoutException
with message 'Read timed out'.
在这种情况下RestTemplate
,当请求超时时,Spring 将抛出ResourceAccessException。该实例下的潜在异常将java.net.SocketTimeoutException
带有消息“读取超时”。