java - CompletableFuture - 并行运行多个休息调用并获得不同的结果
问题描述
我有一个相当普遍或独特的要求。例如,我有以下AccountDetails
列表:
List<AccountDetails>
class AccountDetails {
String bankAccountId;
String mortgageAccountId;
Integer noOfTrans;
String addressLine;
String externalLink;
}
上述所有字段,除了bankAccountId
从外部 REST 服务调用中提取。我想并行调用所有 REST 服务并更新列表中的每个对象:
因此,它如下所示:
对于每个accountDetails
- 调用抵押REST服务并更新
martgageAccountId
字段(REST返回MortgageInfo对象) - 调用事务 REST 服务并更新
noOfTrans
字段(REST 返回Transactions
对象) - 调用地址REST服务和更新
addressLine
字段(REST返回Address
对象) - 调用链接 REST 服务和更新
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();
推荐阅读
- swift - 尝试在 Swift 中将变量的百分比添加到自身
- android - OSM 地图图块未在 Android 版本 8.1 上显示
- php - 频繁的数据库条目 - PHP、MySQLi
- java - OneToOne 与级联删除双方的关系
- javascript - 如何将“componentWillReceiveProps”替换为“getDerivedStateFromProps”?
- javascript - 将 json 符号转换为 html
- chromecast - 是否可以使用 chromecast 将我的谷歌数据工作室报告投射到电视上?
- c++ - 为什么这个程序没有检测到有空格?
- php - PHP CURL 不获取代理(未经身份验证)
- html - :focus-within 仅在使用键盘聚焦按钮时有效,在 Firefox 63 中单击时无效