我有一个相当普遍或独特的要求。例如,我有以下 AccountDetails
列表:List<AccountDetails>
class AccountDetails {
String bankAccountId;
String mortgageAccountId;
Integer noOfTrans;
String addressLine;
String externalLink;
}
上述所有字段,除了 bankAccountId
都是从外部 REST 服务调用中提取的。我想并行调用所有 REST 服务并更新列表中的每个对象:
所以,它看起来像下面:
对于每个
accountDetails
martgageAccountId
字段(REST 返回 MortgageInfo 对象) noOfTrans
字段(REST 返回 Transactions
对象) addressLine
字段(REST 返回 Address
对象) externalLink
字段。 (REST 返回 Links
对象) 我希望并行执行上述所有调用,并针对列表中的每个
AcccountDetails
对象。如果有异常,我想优雅地处理它。请注意,上述每个 REST 服务都返回不同的自定义对象
我对如何使用
CompletableFuture
链接实现这一目标感到困惑。不确定
allOf
或 thenCombine
(只需要两个),或者 thenCompose
应该使用以及如何将所有这些放在一起。任何例子/想法?
最佳答案
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();
关于java - CompletableFuture - 并行运行多个 rest 调用并获得不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62839608/