gpt4 book ai didi

java - CompletableFuture - 并行运行多个 rest 调用并获得不同的结果

转载 作者:行者123 更新时间:2023-12-03 12:48:04 25 4
gpt4 key购买 nike

我有一个相当普遍或独特的要求。例如,我有以下 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 链接实现这一目标感到困惑。
    不确定 allOfthenCombine(只需要两个),或者 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/

    25 4 0