多线程往数据库批量insert
2021-12-11 本文已影响0人
刘小刀tina
@PostMapping
public Object batchInsetAsync(){
ExecutorService executorService = Executors.newFixedThreadPool(10);
int count = LIST.size();
int threadSize = count % 3000 == 0 ? count / 3000 : (count / 3000) + 1;
List<Callable<Boolean>> tasks = new ArrayList<>();
for (int i = 0; i < threadSize; i++) {
//0,3000,3000 6000, 6000 6001
int k = i;
int start = k * 3000;
int index = (k + 1) * 3000;
tasks.add(() -> {
int end = k == threadSize-1 ? count : index;
//业务批量插入
List<Model> models = LIST.subList(start, end);
modelMapper.batchInsert(models);
log.info("currentTime:{},threadName:{}", Instant.now(),Thread.currentThread().getName());
return Boolean.TRUE;
});
}
try {
executorService.invokeAll(tasks);
} catch (InterruptedException e) {
log.error("e:{}",e);
e.printStackTrace();
}
executorService.shutdown();
return "success2222";
}