多线程的事务控制

直接看代码,这是一个多线程生成库存同步任务的,事务控制为一个大的事务,回滚就全部线程的任务不提交全部回滚



private PlatformTransactionManager transactionManager;

(rollbackFor = Exception.class, value = "transactionManagerMysql", propagation = Propagation.NESTED)
    public void mainStockClear1() {
        List<TransactionStatus> transactionStatuses = Collections.synchronizedList(new ArrayList<TransactionStatus>());
        List<DO2oStockUpt> do2oStockUpts = new ArrayList<>();
        AtomicInteger atomicInteger = new AtomicInteger(0);
        for (int i = 0; i < 5; i++) {
            DO2oStockUpt do2oStockUpt = new DO2oStockUpt();
            do2oStockUpt.setOlshopid(1L);
            do2oStockUpt.setTfid(1);
            do2oStockUpt.setBusnoOnline("1");
            do2oStockUpt.setStoreId("1");
            do2oStockUpt.setNumiid("1");
            do2oStockUpt.setSkuid("1");
            do2oStockUpt.setWarecode("1");
            do2oStockUpt.setWareqty(0L);
            do2oStockUpt.setStatus(0);
            do2oStockUpt.setUpdType(1);
            do2oStockUpt.setIsMain(1);
            do2oStockUpt.setCreatetime(new Date());
            do2oStockUpt.setTfid(i);
            do2oStockUpts.add(do2oStockUpt);

            int finalI = i;
            ThreadPoolService.asynchronousTask(()->{
                try {
                    updateStudentsTransaction(transactionManager, transactionStatuses, do2oStockUpt, finalI);
                } catch (Exception e) {
                    e.printStackTrace();
                    atomicInteger.addAndGet(1);
                }
            });
        }

        if (!transactionStatuses.isEmpty()) {
            if (atomicInteger.get() != 0) {
                transactionStatuses.forEach(s -> transactionManager.rollback(s));
            } else {
                transactionStatuses.forEach(s -> transactionManager.commit(s));
            }
        }
    }

    (rollbackFor = Exception.class, value = "transactionManagerMysql", propagation = Propagation.REQUIRES_NEW)
    public void updateStudentsTransaction(PlatformTransactionManager transactionManager,
                                          List<TransactionStatus> transactionStatuses,
                                          DO2oStockUpt do2oStockUpt, Integer i) throws Exception{
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        transactionStatuses.add(status);
        if (i != null && 2 == i) {
            throw new Exception();
        }
        do2oStockUptMapper.insert(do2oStockUpt);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值