赞
踩
网上很多博友都实现了springboot项目的大量数据异步执行插入数据库,这样可以实现先返回给页面执行完成的结果,其实多线程还没有执行完成,现在下面着重介绍一下使用多线程实时导入数据库(阻塞式线程)。
1、线程池的创建
@Configuration
public class ThreadConfig {//implements AsyncConfigurer {
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(1000);
executor.setQueueCapacity(500);
//线程名称前缀
executor.setThreadNamePrefix(“executorService-”);
executor.setKeepAliveSeconds(30000);
executor.initialize();
return executor;
}
}
2、线程接口类的实现
@Service
public class ThrdeadToDBUtil {
@Autowired
private ThreadConfig executorService;
/**
*listDto插入数据库的总list
*主线程计数countDownLatch
*执行sql的dao层也可以作为参数传过来
**/
@Transactional(rollbackFor = Exception.class) public void execSaveCust(XXservices XXservices, List<uc**> listDto,CountDownLatch countDownLatch) { int count = listDto.size() / 4; List<uc**> list = null; //分4个线程执行 for (int i = 1; i <= 4; i++) { int startIndex = (i * count); int endIndex = (i + 1) * count; if (i == 4) { endIndex = listDto.size(); } list = listDto.subList(startIndex, endIndex); List<uc**> finalNewlist = list; System.out.println("线程" + i + "更新" + startIndex + "到" + endIndex); executorService.getAsyncExecutor().execute(() -> { try { //调用数据库实现插入finalNewlist XXservices.save(finalNewlist); } catch (Exception e) { e.printStackTrace(); } finally { countDownLatch.countDown(); } }); }
3、主线程(自己项目中需要调用线程的类中) CountDownLatch countDownLatchCust = new CountDownLatch(4);
try {
thrdeadToDBUtil.execSaveCust(XXservices,uploadCustomerList,countDownLatchCust);
//在主线程最后调用await()方法,这样就能确保所有的子线程运行完后主线程才会继续执行
countDownLatchCust.await();
}catch (Exception e){
e.printStackTrace();
}
遇到的坑–主线程不要和多线程放在一个类,容易失效。–countDownLatchCust 不需要写成静态的,否则执行一次就失效了。–await()设置下时间,不然容易数据错误。
参考地址:https://blog.csdn.net/weixin_34186128/article/details/88754432
异步的调用比较简单,可以参考:https://www.jb51.net/article/187568.htm
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。