背景:批量导入数据时耗时过长
解决方案:使用多线程进行数据保存
步骤:
1.构建需要保存的数据记录(代码略)
List<Object> objectList = new ArrayList<>();
2.拆分总体数据为多份数据
//将原始数据拆分为多个子List,存储在partLists中
List<List<Object>> partLists = new ArrayList<>();
//定义分批的条数
int limitSize = 100;
int size = objectList.size()
//计算出分批数
int part = size % limitSize > 0 ? (size / limitSize + 1) : size / limitSize;
List<Object> partList = new ArrayList<>();
for(int i = 0 ; i < part ; i++){
int fromIndex = i * limitSize;
int toIndex = (i+1) *limitSize > size ? size : (i+1)*limitSize;
partList = objectList.subList(fromIndex,toIndex);
if(partList.size() > 0){
partLists.add(partList);
}
}
3.使用CompletableFuture执行多线程任务
Executor executor = Executors.newFixedThreadPool(10);
//mapper为业务中mybatis的mapper接口 ,mapper.batchInsert(sub)方法返回新增成功的条数
List<CompletableFuture<Integer>> listFuture = objectList.stream().map(sub->CompletableFuture.supplyAsync(
()-> mapper.batchInsert(sub),executor)).collect(Collectors.toList());
//新增成功的条数
int count = 0;
for(CompletableFuture<Integer> c : listFuture){
Integer subCount = c.get();
count += subCount;
}