异步执行,由同一个容器接收结果

167 阅读1分钟
  • 异步执行,异步接收结果
// 1.查询有销售数据的商品
List<Integer> productIdList = productMapper.listConnectSaleProductIds();

// 2.切分商品集合,查询每个商品的最新壳上价格
int getTimes = (int) Math.ceil(Float.valueOf(new BigDecimal(String.valueOf(productIdList.size()))
        .divide(new BigDecimal(String.valueOf(Constants.DB_OPERATE_NUM))).toString()));

List<List<Integer>> batches = new ArrayList<>();
Stream.iterate(0, n -> n + Constants.DB_OPERATE_NUM).limit(getTimes).forEach(a -> batches
        .add(productIdList.stream().skip(a).limit(Constants.DB_OPERATE_NUM).collect(Collectors.toList())));

List<CompletableFuture<List<InitConnectProductPriceDTO>>> futures =
        batches.stream()
                .map(ids -> CompletableFuture.supplyAsync(() ->
                        productMapper.listInitConnectProductPrice(ids), taskExecutor)).collect(Collectors.toList());

List<List<InitConnectProductPriceDTO>> data
        = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
  • 异步执行,同步接收结果
// 1.查询有销售数据的商品
List<Integer> productIdList = productMapper.listConnectSaleProductIds();

// 2.切分商品集合,查询每个商品的最新壳上价格
int getTimes = (int) Math.ceil(Float.valueOf(new BigDecimal(String.valueOf(productIdList.size()))
        .divide(new BigDecimal(String.valueOf(Constants.DB_OPERATE_NUM))).toString()));

List<List<Integer>> batches = new ArrayList<>();
Stream.iterate(0, n -> n + Constants.DB_OPERATE_NUM).limit(getTimes).forEach(a -> batches
        .add(productIdList.stream().skip(a).limit(Constants.DB_OPERATE_NUM).collect(Collectors.toList())));

// 异步查询
List<InitConnectProductPriceDTO> data = new ArrayList<>();
List<String> error = new ArrayList<>();

Stream<CompletableFuture<InitConnectProductPriceDTO>> completableFutureStream = batches.stream().map(ids ->
        CompletableFuture
                .supplyAsync(() -> productMapper.listInitConnectProductPrice(ids), taskExecutor)
                .handle((initConnectProductPriceDTOS, throwable) -> {
                    if (throwable == null) {
                        data.addAll(initConnectProductPriceDTOS);
                    } else {
                        System.err.println(throwable.toString());
                        error.add("1");
                    }
                    return null;
                }));
CompletableFuture[] completableFutures = completableFutureStream.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(completableFutures).whenComplete((x, y) -> System.err.println("完成")).join();

if (error.size() > 0) {
    throw new RollBackException("失败");
}