首页 > 解决方案 > CompletableFuture - 并行运行多个休息调用并获得不同的结果

问题描述

我有一个相当普遍或独特的要求。例如,我有以下AccountDetails列表:

List<AccountDetails>

class AccountDetails {
    String bankAccountId;
    String mortgageAccountId;
    Integer noOfTrans;
    String addressLine;
    String externalLink;   
}

上述所有字段,除了bankAccountId从外部 REST 服务调用中提取。我想并行调用所有 REST 服务并更新列表中的每个对象:

因此,它如下所示:

对于每个accountDetails

我希望所有上述调用并行,并且对于AcccountDetails列表中的每个对象。如果有异常,我想优雅地处理它。请注意,上述每个 REST 服务都返回不同的自定义对象

我对如何通过CompletableFuture链接实现这一点感到困惑。不确定allOf或者thenCombine(只需要两个),或者thenCompose应该使用以及如何将所有这些放在一起。

任何例子/想法?

标签: javamultithreadingspring-bootjava-8completable-future

解决方案


AccountDetails accountDetails = new AccountDetails();

CompletableFuture.allOf(
                        CompletableFuture.
                                supplyAsync(() -> //CALL MORTAGE INFO REST, executor).
                                thenAccept(x -> {
                                    accountDetails.setMortgageAccountId(x.getReqdField())
                                }).
                                handle(//HANDLE GRACEFULLY),
                        CompletableFuture.
                                supplyAsync(() -> //CALL SOME OTHER REST, executor).
                                thenAccept(x -> {
                                    accountDetails.setNoOfTrans(x.getReqdField())
                                }).
                                handle(//HANDLE GRACEFULLY),
                        CompletableFuture.
                                supplyAsync(() -> //CALL SOME INFO REST, executor).
                                thenAccept(x -> {
                                    accountDetails.setAddressLine(x.getReqdField())
                                }).
                                handle(//HANDLE GRACEFULLY),
                        CompletableFuture.
                                supplyAsync(() -> //CALL SOME OTHER REST, executor).
                                thenAccept(x -> {
                                    accountDetails.setExternalLink(x.getReqdField())
                                }).
                                handle(//HANDLE GRACEFULLY),
                ).join();

推荐阅读