【发布时间】:2020-06-16 04:17:00
【问题描述】:
我正在使用 ApacheHttpClient
我有一个 Java 方法(在 Java 微服务中),它向外部端点(我不拥有的端点)发出 Http POST 请求。一切通常都运行良好,但有时端点已关闭并失败。代码看起来像这样(简化):
private HttpResponseData postRequest(String url) throws Exception {
HttpResponseData response = null;
try (InputStream key = MyAPICaller.class.getResourceAsStream(keyPath)) {
MyAPICaller.initializeApiClient(Username, PassString, key);
int attempts = REQUEST_RETRY_COUNT; // starts at 3
while (attempts-- > 0) {
try {
response = MyAPICaller.getInstance().post(url);
break;
} catch (Exception e) {
log.error("Post Request to {} failed. Retries remaining {}", url, attempts);
Thread.sleep(REQUEST_RETRY_DELAY * 1000);
}
}
if (response == null)
throw new Exception("Post request retries exceeded. Unable to complete request.");
}
return response;
}
我没有编写原始代码,但正如您所见,它看起来像是发出请求,而 REQUEST_RETRY_COUNT 大于 0(看起来总是如此) ,它会尝试向 url 发送 post。好像因为某种原因那里有一个断点,所以跳转到try块后,总是会断掉,没有重试机制。
Java 中是否有一个通用的设计模式来实现重试模式以访问外部端点?我知道在 Javascript 中你可以使用 Fetch API 并返回一个 promise,Java 有类似的东西吗?
【问题讨论】:
-
你要达到什么样的 API 端点,是 AWS、GCP 等?
-
重试已经是
ApacheHttpClient的一部分 -
promise 是 JS 代表一个异步操作,promise 本身不会重试失败。