springBoot实现多线程数据插入数据库

网上很多博友都实现了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

  • 4
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值