为啥使用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();