Java 8 acceptEither CompletableFuture示例 [英] Java 8 acceptEither CompletableFuture Example

查看:453
本文介绍了Java 8 acceptEither CompletableFuture示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java 8和Java的新手.在学习CompletableFuture API的过程中. 我还有一个要求,我需要异步调用第三方API&然后等待7秒钟. 7秒后,继续进行我的实际处理. 另外,我需要检查在这7秒钟内Async调用是否已成功完成.如果是,则记录成功响应或异步调用异常完成,然后在我的数据库中记录错误响应.

I'm new to Java 8 & in the process of learning CompletableFuture API. I also have a requirement where I need to make Asynchronous call to Third Party API & then wait for 7 seconds. After 7 seconds, continue with my actual processing. Also I need to check whether in these 7 seconds Async call has completed successfully. If yes then Log Success response or if Async call has completed exceptionally then Log error response in my database.

CompletableFure<Void> thridPartyCallFuture = Async Call to Third Party API;

//Wait for 7 seconds

我不需要从第三方API调用中获取任何响应,我只需要暂停7秒钟即可.

I do not need to retrieve any response from Third Party API call, I just need to pause for 7 seconds.

因此我尝试致电thridPartyCallFuture.get(7, TimeUnit.SECONDS); 但是问题是当我调用thridPartyCallFuture.isDone()时,它将始终返回true,但是如果thridPartyCallFuture异常完成,我将不知道,这对于在DB中记录错误响应很重要.让我们考虑第三方API中断&的情况.我们的电话异常完成.在这种情况下,isDone()将返回true,而isCompletedExceptionally()将返回false.

And so I tried calling thridPartyCallFuture.get(7, TimeUnit.SECONDS); but the problem with this is when I call thridPartyCallFuture.isDone() it will always return true, but in case if thridPartyCallFuture has completed exceptionally, I will not get to know, which is important to log error response in DB. Let's consider a scenario where Third Party API is down & our call had completed exceptionally. In this case isDone() will return true whereas isCompletedExceptionally() will return false.

检查thridPartyCallFuture是否已成功完成,然后在DB中记录成功响应.

Check if thridPartyCallFuture has completed successfully then Log success response in DB.

检查thridPartyCallFuture是否已异常完成,然后在DB中记录错误响应.

Check if thridPartyCallFuture has completed exceptionally then Log error response in DB.

我曾尝试探索acceptEither,但未能正确完成.

I had tried to explore acceptEither but couldn't get it right.

我知道在Java 9中引入了一种新方法orTimeOut(int),但是在Java 8中我们没有这种方法.

I got to know in Java 9 a new method is introduced orTimeOut(int) but in Java 8 we do not have such method.

感谢您的帮助!

谢谢.

推荐答案

即使结果更快返回,也不确定为什么要等待7秒. 以下代码显示了如何处理与API调用有关的问题. 没错,Java 9支持超时更好.

Not sure why you want to wait 7 seconds even if the result came back sooner. The following code shows how to handle problems with the call to the API. And you're right, Java 9 supports timeouts much better.

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示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆