背景:批量导入数据时耗时过长
解决方案:使用多线程进行数据保存
步骤:
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;
}
这篇博客探讨了在批量导入数据时遇到的耗时问题,并提出了通过多线程来解决的方案。首先,将数据拆分成多个子List,然后利用CompletableFuture和固定线程池执行批处理插入操作,显著提高了数据保存的效率。该方法适用于大数据量导入场景,能有效减少导入时间。
6175

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



