您好,我正在使用 spring RestTemplate
来调用 REST API。 API 可能非常缓慢甚至离线。我的应用程序通过一个接一个地发送数千个请求来构建缓存。响应也可能很慢,因为它们包含大量数据。
我已经将超时时间增加到 120 秒。我现在的问题是 API 可以脱机并且我得到一个 org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
异常。
API离线的情况下,应用程序应该等待并重试,直到API再次在线。
我可以在 RestTemplate
中实现这一点,而无需自己构建异常循环吗?
谢谢!
最佳答案
我有同样的情况,并做了一些谷歌搜索找到了解决方案。给出答案,希望对其他人有所帮助。您可以为每次尝试设置最大尝试和时间间隔。
@Bean
public RetryTemplate retryTemplate() {
int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt"));
int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval"));
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempt);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(retryTimeInterval); // 1.5 seconds
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
下面是我要执行的休息服务。
retryTemplate.execute(context -> {
System.out.println("inside retry method");
ResponseEntity<?> requestData = RestTemplateProvider.getInstance().postAsNewRequest(bundle, ServiceResponse.class, serivceURL,
CommonUtils.getHeader("APP_Name"));
_LOGGER.info("Response ..."+ requestData);
throw new IllegalStateException("Something went wrong");
});
关于java - 如果主机离线,重试 java RestTemplate HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32352484/