实现CompletableFuture的返回数据,放入每个list中

为啥使用CompletableFuture

有时候我们后端接口,可能会有多个查询,而且这些查询是互不关联的,使用串行的方式,在数据量不大的时候,时间没什么影响,但是在数据量大的时候,使用CompletableFuture也是一种提高效率的方法

 //获取存款
        CompletableFuture<List<Map<String, Object>>> balanceFuture = CompletableFuture.supplyAsync(() -> {
            List<Map<String, Object>> mapList = businessMapper.getDepositsByName(param1);
            return mapList;
        });
        //获取贷款
        CompletableFuture<List<Map<String, Object>>> tableInFuture = CompletableFuture.supplyAsync(() -> {
            List<Map<String, Object>> mapListB = businessMapper.getDepositsByName(param2);
            return mapListB;
        });
        //等balanceFuture tableInFuture 两个任务都执行完
        CompletableFuture.allOf(balanceFuture,tableInFuture);
            List<Map<String, Object>> mapList = balanceFuture.join();
        List<Map<String, Object>> mapListB = tableInFuture.join();

如上,使用CompletableFuture查询存款和贷款的,使用了异步,所以两个sql的时间不会累加。
下面还有一种是使用在for循环中,当然一般是不能把查询放入for循环中的,但是如果实在需要,也是可以用CompletableFuture的

 List<Map<String,Object>> list = userMapper.groupMonthCount(year);
        List<CompletableFuture<List<Map<String, Object>>>> futures = new ArrayList<>();

        for (Map<String, Object> map : list) {
            Object month = map.get("MONTH");
            futures.add(CompletableFuture.supplyAsync(() -> {
                List<Map<String, Object>> dayList = userMapper.groupDayCount(year + month);
                return dayList;
            }).thenApply(dayList -> {
                map.put("echartData", dayList);
                return dayList;
            }));
        }
        //等待全部完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-13 05:52:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-13 05:52:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-13 05:52:03       82 阅读
  4. Python语言-面向对象

    2023-12-13 05:52:03       91 阅读

热门阅读

  1. Audio Signal (MATLAB)代码学习——常见问题4

    2023-12-13 05:52:03       46 阅读
  2. 【Ubuntu】linux常用的录屏软件

    2023-12-13 05:52:03       58 阅读
  3. Ubuntu 22.04 安装 OCI CLI

    2023-12-13 05:52:03       45 阅读
  4. 在React中使用动态图标

    2023-12-13 05:52:03       65 阅读
  5. 什么是PHP的动态类型?

    2023-12-13 05:52:03       65 阅读
  6. 微信小程序:按钮禁用,避免按钮重复提交

    2023-12-13 05:52:03       51 阅读
  7. 使用ansible批量初始化服务器

    2023-12-13 05:52:03       56 阅读