简体   繁体   English

Java8 CompletableFuture条件链接

[英]Java8 CompletableFuture conditional chaining

I have read many java8 completable future tutorials, most of them are basically same. 我已经阅读了很多java8可完成的未来教程,其中大部分基本相同。 All talking about some basic method "thenAccept"/"thenApply"/thenCombine" to build a pipeline flow. 所有谈论一些基本方法“thenAccept”/“thenApply”/ thenCombine“构建管道流程。

But when come to a real work problem, I feel hard to organize different completable futures from different Service. 但是当遇到真正的工作问题时,我觉得很难从不同的服务部门组织不同的可完成的未来。 For Example: 例如:

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


   interface DB{
       Completable<Bean> getAsync(long id)
    }

the service logic is quite simple, get data from Cache, if exist return to our client, if not, get it from DB, if exist save it back to Cache, and return it to our client, if neither exist in DB, return "error" to client. 服务逻辑非常简单,从Cache获取数据,如果存在则返回我们的客户端,如果不存在,则从DB获取,如果存在则将其保存回Cache,并将其返回给我们的客户端,如果DB中既不存在,则返回“错误“给客户。

using synchronize API, it will be quite straight ahead. 使用同步API,它将非常直接。 But when using asyncnorized API, there are "many pipelines", manny conditional break. 但是当使用asyncnorized API时,有“很多管道”,manny条件中断。 I can not figure out how to implement this using CompletableFuture API. 我无法弄清楚如何使用CompletableFuture API实现它。

If you don't care about the result of saving into the cache and if you want to throw an exception on bean not found, then it can be eg 如果你不关心保存到缓存的结果,如果你想在未找到的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;
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM