多线程事务统一提交与回滚

大数据量操作时,多线程提升系统性能,可以利用线程池和CountDownLatch,多线程并发处理批量数据,实现多线程事务回滚,事务补偿。

package com.example.springbootdemo.threadTransaction.service.impl;

import com.example.springbootdemo.threadTransaction.mapping.TxUserMapper;
import com.example.springbootdemo.threadTransaction.service.TxUpdateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class TxUpdateServiceImpl implements TxUpdateService {

    @Autowired
    private TxUserMapper userMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    public boolean update(Integer id, String name) {
        // 线程计数器
        CountDownLatch threadLatch = new CountDownLatch(3);
        // 线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        // 异常监测
        AtomicBoolean isError = new AtomicBoolean(false);
        AtomicInteger integer = new AtomicInteger(0);
        // 模拟3批次的数据处理
        for (int i = 0; i < 3; i++) {
            pool.execute(() -> {
                try {
                    final int get = integer.addAndGet(1);
                    boolean doUpdate = doUpdate(id + get, name, isError, threadLatch);
                } catch (Exception e) {
                    log.error("出错啦", e);
                    isError.set(true);
                }
            });
        }
        try {
            threadLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdown();
        return true;
    }

    public boolean doUpdate(Integer id, String name, AtomicBoolean isError, CountDownLatch threadLatch) throws InterruptedException {
        Integer update = null;
        // 开启事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
	        // 执行sql
            update = userMapper.update(id, name);
            // 模拟数据处理耗时
            Thread.sleep(id * 1000);
            // 模拟处理中出现异常
            if (id == 1) {
                isError.set(true);
            }
        } finally {
	        // 标识线程执行完毕
            threadLatch.countDown();
        }
        // 等待所有线程执行完毕
        threadLatch.await();
        if (isError.get()) {
            log.info("线程:{}检测到异常,事务回滚", Thread.currentThread().getName());
            transactionManager.rollback(status);
        } else {
            log.info("线程:{}正常执行完毕,事务提交", Thread.currentThread().getName());
            transactionManager.commit(status);
        }
        return update > 0;
    }
}

数据库修改前
在这里插入图片描述
写一个接口,模拟网络请求,在执行中出错所有事务回滚,数据库数据无变化
在这里插入图片描述
修改标识出错的代码,保证所有线程正常执行

            if (id == 10) {
                isError.set(true);
            }

模拟网络请求,在执行中正常执行,所有事务提交,数据库数据已变
在这里插入图片描述
修改后的数据库数据
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值