如何在正常响应时间之前中断无响应的RestTemplate调用



下面是我们对第三方服务的调用:

try {
ResponseEntity<String> response = new RestTemplate().exchange(
requestUrl,
HttpMethod.POST,
new HttpEntity<String>(null, new HttpHeaders()),
String.class);
// Log the response received (and request sent) 
log.info(String.format("3rd party response: %s for request: %s" + response, requestUrl));
} catch (CustomTimeoutException e) {
log.error(String.format("Call to 3rd party with %s failed with: %s", requestUrl, e));
}

如果请求的服务不可用,则需要30秒才能超时。我们无法控制他们的超时时间,所以如果我们在3秒内没有收到回复,我们希望抛出、捕获并处理自定义异常。

对线程处理不是很有经验,所以如果能提供一个具体的例子来说明这个特定的代码将如何融入解决方案,我们将不胜感激。

我们无法控制他们的超时时间

不关心服务器超时。作为HTTP客户端,您可以在两个不同的级别上定义自己的超时:

  • 连接超时:到达目标服务器的最长时间
  • 读取超时:允许您在一段时间后(可能早于服务器中止的时间(放弃,以防HTTP响应没有到来

请参阅Spring文档,了解如何配置这两个超时。

最新更新