spring多线程数据批量导入

每个线程事务独立,所有线程最终确定提交或回滚。

@Autowired
private DataSourceTransactionManager transactionManager;

@Override
public String importUserAcctParallel(List<UserImportDTO> userList, String operName) {
    // 导入数据总量
    int size = userList.size();
    // 线程数量
    int threadCount = size > 200 ? 10 : 5;
    // 每个线程处理的数据量
    int threadHandleCount = (int) Math.ceil(size / (double) threadCount);

    /* 
     * 使用倒计时器控制所有线程同步
     * 使线程任务完成之后等待其他的线程
     * 当所有的线程都处理完成之后 
     * 再一起判断是commit还是rollback
     * 
     */
    CountDownLatch cdl = new CountDownLatch(threadCount);
    // 数据指针
    AtomicInteger ci = new AtomicInteger(0);
    // 是否出现错误
    AtomicReference<Boolean> isError = new AtomicReference<>(false);
    // 错误信息 因为涉及到了多线程所以使用了同步锁列表
    List<UserImportMsgDTO> msgDTOList = Collections.synchronizedList(new ArrayList<>());

    for (int j = 0; j < threadCount; j++) {
        threadPoolTaskExecutor.execute(() -> {
            // 申明事务
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            TransactionStatus status = transactionManager.getTransaction(def);
            
            for (int i = 0; i < threadHandleCount; i++) {
                // 判断是否出现了错误,若有错误直接中断
                if (Boolean.TRUE.equals(isError.get())) {
                    break;
                }
                int idx = ci.getAndIncrement();
                if (idx >= size) {
                    break;
                }
                // 具体数据处理
                String msg = handleImportItem(userList.get(idx), sysPosts, workNumMap, defaultPwd);
                
                if (msg != null) {
                    /* 出现错误
                     * 记录错误信息、标记错误
                     */
                    UserImportMsgDTO dto = new UserImportMsgDTO();
                    dto.setRowNum(idx + 2);
                    dto.setMsg(msg);
                    msgDTOList.add(dto);
                    isError.set(true);
                    break;
                }
            }
            // 当前线程任务处理完毕
            cdl.countDown();
            try {
                // 等待其他线程完成任务
                cdl.await();
            } catch (InterruptedException e) {
                log.error(" CountDownLatch await error : {}", e.getMessage());
            }

            if (Boolean.TRUE.equals(isError.get())) {
                // 回滚事务
                transactionManager.rollback(status);
            } else {
                transactionManager.commit(status);
            }
        });
        
    }
    try {
        // 主线程等待子线程处理数据
        cdl.await();
    } catch (InterruptedException e) {
        log.error(" CountDownLatch await error : {}", e.getMessage());
    }
    if (Boolean.TRUE.equals(isError.get())) {
        // 若有错误 返回错误信息
        workNumService.quitQuickMode(null);
        msgDTOList.sort(Comparator.comparingInt(UserImportMsgDTO::getRowNum));
        String collect = msgDTOList.stream()
                .map(i -> MessageFormat.format("<br/> 数据第 {0} 行 导入失败:{1}", i.getRowNum(), i.getMsg()))
                .collect(Collectors.joining());
        String res = MessageFormat.format("很抱歉,导入失败!共 {0} 条数据格式不正确,错误如下:{1}", msgDTOList.size(), collect);
        throw new BusinessException(res);
    } else {
        // 成功返回
        workNumService.quitQuickMode(workNumMap);
        return "恭喜您,数据已全部导入成功!共 " + size + " 条 ";
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值