CompletableFuture异步查询分页接口,拼装返回结果

//2.否则异步分批次获取 分N次调用接口,获取数据,然后拼装返回。
Long total = rpcResult.getResult().getPageItemTotal();int totalPage =  (int) Math.ceil((double) req.getPageSize() / allowMaxPageSize);
List<CompletableFuture<List<PlanOrderDetailFromVcRes>>> futures = new ArrayList<>();for (int currentPage = 1; currentPage <= totalPage; currentPage++) {
    //用于lambda 表达式内部必须是final,所以currentPage不能直接用, 为每个线程创建新的finalCurrentPage
    int finalCurrentPage = currentPage;
    //由于gisOrderParam是共享的,set内容 有多线程安全问题,所以为每个线程新new一个 localParam
    PlanOrderDetailFromVcReq localParam = new PlanOrderDetailFromVcReq();
    BeanUtils.copyProperties(req, localParam);
    //每个分页查询都会被包装成一个CompletableFuture,并提交给线程池进行异步处理
    CompletableFuture<List<PlanOrderDetailFromVcRes>> future = CompletableFuture.supplyAsync(() -> {
        localParam.setPageIndex(finalCurrentPage);
        localParam.setPageSize(allowMaxPageSize);
        return getPageData(req,finalCurrentPage,allowMaxPageSize);
    }).exceptionally(e -> {
        log.error(" 查询订单信息异常", e);
        return Collections.emptyList();
    });
    futures.add(future);
}

//使用CompletableFuture.allOf()等待所有任务完成,然后将结果合并到最终的list中
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
        .thenAccept(v -> {
            for (CompletableFuture<List<PlanOrderDetailFromVcRes>> future : futures) {
                try {
                    List<PlanOrderDetailFromVcRes> orderInfoList = future.get();
                    if (CollectionUtils.isNotEmpty(orderInfoList)) {
                        list.addAll(orderInfoList);
                    }
                }
                catch (Exception e) {
                    log.info("交货计划查询 分批查询异常");
                }
            }
        })
        .join();

 

posted @ 2024-12-26 13:27  架构之路  阅读(120)  评论(0)    收藏  举报
========================================================================== 如果您觉得这篇文章对你有帮助,可以【关注我】或者【点赞】,希望我们一起在架构的路上,并肩齐行 ==========================================================================