CompletableFuture的thenCombine结果组合用法实例

CompletableFuture的thenCombine结果组合用法实例

thenCombine 方法,合并两个线程任务的结果,并进一步处理。有种大数的MapReduce的思想。
CompletableFuture的thenCombine结果组合用法实例_第1张图片

举例:

    @Autowired
    @Qualifier(ThreadPoolConfig.IMPORT_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

定义线程池。并在CompletableFuture中指定线程池。也可以不指定线程池,没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。

如果所有 CompletableFuture 共享一个线程池,那么一旦有任务执行一些很慢的 I/O 操作,就会导致线程池中所有线程都阻塞在 I/O 操作上,从而造成线程饥饿,进而影响整个系统的性能。所以,建议根据不同的业务类型创建不同的线程池,以避免互相干扰

1. demo

public List<Object> queryRecentOrders(String custNo) {
        CompletableFuture<List<Integer>> future1 = CompletableFuture
                .supplyAsync(() -> {
                    int number = 1;
                    List<Integer> integers = Lists.newArrayList(number);
                    System.out.println("first:" + integers);
                    return integers;
                }, threadPoolTaskExecutor);

        CompletableFuture<List<Integer>> future2 = CompletableFuture
                .supplyAsync(new Supplier<List<Integer>>() {
                    @Override
                    public List<Integer> get() {
                        int number = 2;
                        List<Integer> integers = Lists.newArrayList(number);
                        System.out.println("second:" + integers);
                        return integers;
                    }
                }, threadPoolTaskExecutor);

        CompletableFuture<List<Integer>> future3 = CompletableFuture
                .supplyAsync(new Supplier<List<Integer>>() {
                    @Override
                    public List<Integer> get() {
                        int number = 3;
                        List<Integer> integers = Lists.newArrayList(number);
                        System.out.println("third:" + integers);
                        return integers;
                    }
                }, threadPoolTaskExecutor);

        CompletableFuture<Integer> result = future1
                .thenCombine(future2, (x, y) -> {
                    System.err.println("x:" + x);
                    System.err.println("y:" + y);
                    Integer sum = Lists.newArrayList(x, y).stream().flatMap(k -> k.stream()).reduce(0, Integer::sum);
                    return sum;
                }).thenCombine(future3, (x, y) -> {
                    System.err.println("x:" + x);
                    System.err.println("y:" + y);
                    y.add(x);
                    Integer reduce = y.stream().reduce(0, Integer::sum);
                    return reduce;
                });

        try {
            Integer integer = result.get();
            System.err.println(integer+"-----------------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return null;

    }

2. 实例

 /**
     * 加速卡
     * 自营会员
     * 拿钱卡
     * 车主卡
     * 省钱卡
     * Vplus
     * 全能
     */
    public List<RightOrderDto> queryRecentOrders(String custNo) {
        Date beforeDate = DateUtil.offsetDay(DateUtil.beginOfDay(new Date()), -7);
        //加速卡
        CompletableFuture<List<RightOrderDto>> future1 = CompletableFuture
                .supplyAsync(() -> {
                    List<TQuickenCardOrder> tCuserLoanRightOrders = cbsQuickenCardService.queryRecentOrders(custNo, beforeDate);
                    List<RightOrderDto> collect = tCuserLoanRightOrders.stream().filter(Objects::nonNull).map(k -> {
                        RightOrderDto orderDto = RightOrderDto.builder()
                                .orderId(k.getId()).orderName(k.getOrderName())
                                .createDatetime(k.getCreateDatetime()).businessType(ComplaintBusinessType.QUICKEN_CARD.getCode())
                                .build();
                        return orderDto;
                    }).collect(Collectors.toList());
                    return collect;
                }, threadPoolTaskExecutor);
        //自营
        CompletableFuture<List<RightOrderDto>> future2 = CompletableFuture
                .supplyAsync(() -> {
                    List<VipOwnOrderResponse> xsqyOrders = cbsVipUserOwnService.queryRecentOrders(custNo, beforeDate);
                    List<RightOrderDto> collect = xsqyOrders.stream().filter(Objects::nonNull).map(k -> {
                        RightOrderDto orderDto = RightOrderDto.builder()
                                .orderId(k.getId()).orderName(k.getOrderName())
                                .createDatetime(k.getCreateDatetime()).businessType(ComplaintBusinessType.SELFSUPPORT.getCode())
                                .build();
                        return orderDto;
                    }).collect(Collectors.toList());
                    return collect;
                }, threadPoolTaskExecutor);
        //拿钱卡
        CompletableFuture<List<RightOrderDto>> future3 = CompletableFuture
                .supplyAsync(() -> {
                    List<GetMoneyCardOrderOmsResp> tCuserLoanRightOrders = cbsGetMoneyCardService.queryRecentOrders(custNo, beforeDate);
                    List<RightOrderDto> collect = tCuserLoanRightOrders.stream().filter(Objects::nonNull).map(k -> {
                        RightOrderDto orderDto = RightOrderDto.builder()
                                .orderId(k.getId()).orderName(k.getCardName())
                                .createDatetime(k.getCreateDatetime()).businessType(ComplaintBusinessType.GET_MONEY.getCode())
                                .build();
                        return orderDto;
                    }).collect(Collectors.toList());
                    return collect;
                }, threadPoolTaskExecutor);
        /**
         * 省钱卡  merchant_no in ('指北','橡树')
         * 车主卡  merchant_no = '车主'
         */
        List<String> sqk = Lists.newArrayList(MerchantNoEnum.XIANGSHU.getCode(), MerchantNoEnum.ZHIBEI.getCode());
        List<String> czk = Lists.newArrayList(MerchantNoEnum.CHEZHU.getCode());
        CompletableFuture<List<RightOrderDto>> future4 = CompletableFuture
                .supplyAsync(() -> {
                    List<TSaveMoneyCardOrder> tCuserLoanRightOrders = cbsSaveMoneyCardService.queryRecentOrders(custNo, beforeDate);
                    List<RightOrderDto> collect = tCuserLoanRightOrders.stream().filter(Objects::nonNull).map(k -> {
                        String orderName = null;
                        String businessType = null;
                        if (sqk.contains(k.getMerchantNo())) {
                            orderName = "省钱卡";
                            businessType = ComplaintBusinessType.SAVEMONEYCARD.getCode();
                        }
                        if (czk.contains(k.getMerchantNo())) {
                            orderName = "车主卡";
                            businessType = ComplaintBusinessType.CARCARD.getCode();
                        }
                        RightOrderDto orderDto = RightOrderDto.builder()
                                .orderId(k.getOrderNo()).orderName(orderName)
                                .createDatetime(k.getCreateDatetime()).businessType(businessType)
                                .build();
                        return orderDto;
                    }).collect(Collectors.toList());
                    return collect;
                }, threadPoolTaskExecutor);


        //vplus 和 全能
        CompletableFuture<List<RightOrderDto>> future5 = CompletableFuture
                .supplyAsync(() -> {
                    List<TCardOrder> xsqyOrders = tCardOrderService.queryRecentOrders(custNo, beforeDate);
                    List<RightOrderDto> collect = xsqyOrders.stream().filter(Objects::nonNull).map(k -> {
                        String businessType = null;
                        if ("Vplus".equals(k.getProductType())) {
                            businessType = ComplaintBusinessType.VPLUS.getCode();
                        }
                        if ("qnk".equals(k.getProductType())) {
                            businessType = ComplaintBusinessType.QNK.getCode();
                        }
                        RightOrderDto orderDto = RightOrderDto.builder()
                                .orderId(k.getOrderNo()).orderName(k.getOrderName())
                                .createDatetime(k.getCreateDatetime()).businessType(businessType)
                                .build();
                        return orderDto;
                    }).collect(Collectors.toList());
                    return collect;
                }, threadPoolTaskExecutor);

        CompletableFuture<List<RightOrderDto>> result = future1
                .thenCombine(future2, (x, y) -> Lists.newArrayList(x, y).stream().filter(Objects::nonNull).flatMap(k -> k.stream()).collect(Collectors.toList()))
                .thenCombine(future3, (x, y) -> Lists.newArrayList(x, y).stream().filter(Objects::nonNull).flatMap(k -> k.stream()).collect(Collectors.toList()))
                .thenCombine(future4, (x, y) -> Lists.newArrayList(x, y).stream().filter(Objects::nonNull).flatMap(k -> k.stream()).collect(Collectors.toList()))
                .thenCombine(future5, (x, y) -> Lists.newArrayList(x, y).stream().filter(Objects::nonNull).flatMap(k -> k.stream()).collect(Collectors.toList()));
        try {
            return result.get();
        } catch (Exception e) {
            logger.error("custNo:{}执行cbs获取权益卡信息出现异常e:{}", custNo, e);
        }
        return null;

    }

总结

thenCombine 用法,是将任务用多线程分组执行再组合。在项目实战中应用场景还是比较多的。

你可能感兴趣的:(java,并发编程之美,windows)