在可完成的未来内循环异步调用可完成的未来

时间:2018-11-30 10:48:12

标签: java completable-future completion-stage

有3个服务都是REST调用-serviceOne,serviceTwo和serviceThree。 serviceTwo处理依赖于serviceOne和serviceThree的输出。但是,serviceThree需要循环运行。

我希望有一种方法可以在serviceThreeRespCF可完成的将来完成后获得最终的响应。当前,在service3完成处理之前会返回planResponse。

我尝试将join()用于serviceThreeRespCF,但没有帮助。是否有更好的方法可以做到这一点,即不使用get()或join()?

public CompletionStage<PlansResponse> process() {

    final PlansResponse plansResponse = new PlansResponse();
    final CompletableFuture<PlansResponse> plansResp = new CompletableFuture<>();

    final CompletionStage<ServiceOneResp> serviceOneRespCF = getResp1(); <A REST CALL>

    return serviceOneRespCF.thenCompose(serviceOneResp -> {

        // function to validate service one resp

        if (condition based on validation)
        {
            List<Plans> plans = serviceOneResp.getPlans();
            if (condition) {
               plansResponse.setSysMsgs());
            }
            else {

                final CompletionStage<ServiceTwoResp> serviceTwoRespCF = getResp2(); <A REST CALL>
                serviceTwoRespCF.thenCompose(serviceTwoResp -> {

                    plans.parallelStream().forEach(plan -> {

                        if (Optional.ofNullable(plan.getPlanId()).isPresent()) {

                            final CompletionStage<ServiceThreeResp> serviceThreeRespCF = getResp3();  <A REST CALL>

                            serviceThreeRespCF.thenAcceptAsync(serviceThreeResp -> {

                                Set<PlanDetail> planDetails = new HashSet<>();
                                planDetails = populatePlanDetails(plan, serviceTwoResp, serviceThreeResp, planDetails);
                                planDetailsList.addAll(planDetails.stream().distinct().collect(Collectors.toList()));
                                plansResponse.setPlanDetails(planDetailsList);
                                planDetails.clear();

                            });
                        }
                    });
                    return serviceThreeRespCF;
                });
            }
        }
        plansResp.complete(plansResponse);
        return plansResp;
    });
}

编辑1 : 尝试加入(return语句是上面代码的延续)

  1. 直接在serviceThreeRespCF上

     return serviceThreeRespCF;
                }).toCompletableFuture().join();
    
  2. 使用thenRunAsync

    return serviceThreeRespCF;
                }).thenRunAsync(() -> {
                    serviceThreeRespCF.toCompletableFuture().join();
                });
    

编辑2 :我尝试使用allOf在可完成的将来获取service3完成阶段的值。 (这是服务2之后组成的)。可以看出,service2响应在此可完成的将来不可用,并且不起作用。除此之外,这涉及必须遍历计划列表2次。还有另一种方法吗?

CompletableFuture<List<Service3Response>> service3ResponseList = allAsList(futures);
service3ResponseList.thenAccept(service3Responses -> {
    AtomicInteger i = new AtomicInteger(0);
    plans.parallelStream().forEach(plan -> {
        Set<PlanDetail> planDetails = new HashSet<>();
        planDetails = populatePlanDetails(acctSetFromRequest, plan, service3Responses.get(i.get()), service2Response <NOT AVAILABLE>, planDetails, acctMapFromResponse.get(plan.getPlanId()));
        planDetailsList.addAll(planDetails.stream().distinct().collect(Collectors.toList()));
        plansResponse.setDistributionPlanDetails(planDetailsList);
        planDetails.clear();
        i.addAndGet(1);
    });
});

public <T> CompletableFuture<List<T>> allAsList(final List<CompletableFuture<T>> futures) {
    return CompletableFuture.allOf(
            futures.toArray(new CompletableFuture[futures.size()])
    ).thenApply(ignored ->
            futures.stream().map(CompletableFuture::join).collect(Collectors.toList())
    );
}

0 个答案:

没有答案