实现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();
相关推荐
f***R86 小时前
HeidiSQL导入与导出数据
java
q***71019 小时前
Spring Boot(快速上手)
java·spring boot·后端
better_liang11 小时前
每日Java面试场景题知识点之-分布式事务处理
java·微服务·面试·springcloud·分布式事务
L***d67013 小时前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
凌波粒13 小时前
Springboot基础教程(3)--自动装配原理/静态资源处理/欢迎页
java·spring boot·后端
likuolei13 小时前
XSL-FO 软件
java·开发语言·前端·数据库
凌波粒13 小时前
SpringBoot基础教程(2)--yaml/配置文件注入/数据校验/多环境配置
java·spring boot·后端·spring
S***267513 小时前
Spring Boot环境配置
java·spring boot·后端
6***830513 小时前
什么是Spring Boot 应用开发?
java·spring boot·后端
毕设源码柳学姐13 小时前
计算机毕设 java 智慧社区服务系统 SSM 框架社区生活平台 Java 开发的便民服务与互动系统
java·开发语言·生活