我是 Java 8 的新手,正在学习 CompletableFuture API。 我还有一个要求,我需要异步调用第三方 API,然后等待 7 秒。 7秒后,继续我的实际处理。 我还需要检查这 7 秒内异步调用是否已成功完成。如果是,则记录成功响应,或者如果异步调用异常完成,则在我的数据库中记录错误响应。
CompletableFure<Void> thridPartyCallFuture = Async Call to Third Party API;
//Wait for 7 seconds
我不需要从第三方 API 调用检索任何响应,我只需要暂停 7 秒。
所以我尝试调用 thridPartyCallFuture.get(7, TimeUnit.SECONDS);
但问题是,当我调用 thridPartyCallFuture.isDone() 时,它总是返回 true,但如果 thridPartyCallFuture 异常完成,我将无法知道,这对于在数据库中记录错误响应很重要。让我们考虑这样一个场景:第三方 API 已关闭并且我们的调用异常完成。在这种情况下,isDone()
将返回 true
,而 isCompletedExceptionally()
将返回 false
。
检查 thridPartyCallFuture 是否已成功完成,然后在数据库中记录成功响应。
检查 thridPartyCallFuture 是否异常完成,然后在数据库中记录错误响应。
我曾尝试探索 acceptEither
但未能成功。
我知道在 Java 9 中引入了一个新方法 orTimeOut(int)
但在 Java 8 中我们没有这样的方法。
感谢任何帮助!
提前致谢。
最佳答案
不知道为什么要等待 7 秒,即使结果返回得更早。 以下代码显示如何处理 API 调用问题。 你是对的,Java 9 对超时的支持要好得多。
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Result> completableFuture = CompletableFuture
.supplyAsync(() -> {
System.out.println("Making call to API...");
//call API here and if call fails, throw exception
//throw new RuntimeException("HTTP call failed");
return new Result(true, "Done");
})
.handle((o, throwable) -> o.isSuccess() ? o : new Result(false, throwable.getMessage()));
Executors.newSingleThreadScheduledExecutor()
.schedule(() -> {
Result result = completableFuture.getNow(new Result(false, "Timeout"));
System.out.println("Log to DB: "
+ result.isSuccess()
+ result.getMessage());
//other application method calls here
}, 7, TimeUnit.SECONDS);
}
--
public class Result {
private boolean success;
private String message;
public Result(boolean success, String message) {
this.success = success;
this.message = message;
}
//getters/setters
}
关于Java 8 AcceptEither CompletableFuture 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52697314/