Java8 CompletableFuture条件链接

jun*_*ang 4 java concurrency java-8 completable-future

我已经阅读了很多java8可完成的未来教程,其中大部分基本相同.所有谈论一些基本方法"thenAccept"/"thenApply"/ thenCombine"构建管道流程.

但是当遇到真正的工作问题时,我觉得很难从不同的服务部门组织不同的可完成的未来.例如:

    interface Cache{
       CompletableFuture<Bean> getAsync(long id);
       CompletableFuture<Boolean> saveAsync(Bean bean);
    }


   interface DB{
       Completable<Bean> getAsync(long id)
    }
Run Code Online (Sandbox Code Playgroud)

服务逻辑非常简单,从Cache获取数据,如果存在则返回我们的客户端,如果不存在,则从DB获取,如果存在则将其保存回Cache,并将其返回给我们的客户端,如果DB中既不存在,则返回"错误"给客户.

使用同步API,它将非常直接.但是当使用asyncnorized API时,有"很多管道",manny条件中断.我无法弄清楚如何使用CompletableFuture API实现它.

sta*_*off 6

如果你不关心保存到缓存的结果,如果你想在未找到的bean上抛出异常,那么它可以是例如

CompletableFuture<Bean> findBeanAsync(long id, Cache cache, DB db) {
    return cache.getAsync(id).thenCompose(bean -> {
        if (bean != null) {
            return CompletableFuture.completedFuture(bean);
        }
        return db.getAsync(id).thenApply(dbBean -> {
            if (dbBean == null) {
                throw new RuntimeException("bean not found with id " + id);
            }
            cache.saveAsync(dbBean);
            return dbBean;
        });
    });
}
Run Code Online (Sandbox Code Playgroud)