背景:导出时,可能导出几千条数据,sql方面无法优化,采用多线程分批次查数据,最后返回
目录
一、sql无法优化
1:对于导出联查表太多,同时都需作为搜索条件,无法从sql层次来进行优化
二、使用多线程
1:springboot项目启动时,默认就有闲置的线程池,会自动销毁,我们只需要开启多线程方法即可
2:如果是有事务需要的多线程,需要注入自己,防止aop失效
3:多线程开启是无法直接返回值的,需要用Future返回,放入到线程中,直接放入查询出的list即可,可以使用工具类来进行构造
new AsyncResult<>(selectMaterialsWareAllVoList(wareAllVo));
@Async
public Future<List<WareAllVo>> selectAsyncWareAllVo(WareAllVo wareAllVo, int pageSize, int pageNum) {
PageUtils.clearPage();
PageUtils.startPage(pageSize,pageNum);
return new AsyncResult<>(selectMaterialsWareAllVoList(wareAllVo));
}
三:分批次查询
1:可以指定批次查询,比如一次查50条
2:外层使用Future<List>的List放入值,最后遍历循环取值即可
future.get()即为取得存入线程中的值,需抓捕异常
public List<WareAllVo> exportWareAllVoList(WareAllVo wareAllVo) {
List<Integer> countList=materialsWareMapper.getWareAllVoCount(wareAllVo);
if(CollectionUtils.isEmpty(countList)){
return new ArrayList<>();
}
List<WareAllVo> list=new ArrayList<>();
int pageSize=50;
List<Future<List<WareAllVo>>> futureList = new ArrayList<>();
int sumPage = countList.size() / pageSize;
for (int i = 1; i < sumPage+2; i++) {
futureList.add(thisService.selectAsyncWareAllVo(wareAllVo, i, pageSize));
}
for (Future<List<WareAllVo>> feture : futureList) {
try {
list.addAll(feture.get());
}catch (Exception e){
throw new ServiceException("物资入库数据处理异常");
}
}
return list;
}
总结
优化性能:sql>多线程>逻辑处理
1262

被折叠的 条评论
为什么被折叠?



