多线程事务控制,简单易懂

核心:通过设置使用的链接自动提交为false,发生错误/结果不符合预期就手动回滚

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

@Slf4j
@RequiredArgsConstructor
public class PlanGoodsExtendFeignImpl implements PlanGoodsExtendFeign {

	// 获取数据库连接,获取会话(内部自有事务)
    private final SqlSessionFactory sqlSessionFactory;
    // 注入线程池
    private final ExecutorService planGoodsExtendThreadPool;
    @Override
    public void test() {
        SqlSession sqlSession = SqlSessionUtils.getSqlSession(sqlSessionFactory);
        Connection connection = sqlSession.getConnection();
        try {
            // 设置手动提交
            connection.setAutoCommit(false);
            SpecialGoodsErrorMapper specialGoodsErrorMapper = sqlSession.getMapper(SpecialGoodsErrorMapper.class);
            //先做删除操作
            specialGoodsErrorMapper.delete(null);
            //模拟数据
            List<Callable<Integer>> callableList = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                SpecialGoodsError specialGoodsError = new SpecialGoodsError();
                specialGoodsError.setProductSelectedId((long) i);
                specialGoodsError.setImportVersion((long) i);
                specialGoodsError.setCode(i + "");
                specialGoodsError.setMessage(i + "");
                Callable<Integer> callable = () -> specialGoodsErrorMapper.insert(specialGoodsError);
                callableList.add(callable);
            }
            //测试报错
            // Callable<Integer> callable = () -> {
            //    return 1 / 0;
            // };
            // callableList.add(callable);
            //执行子线程
            List<Future<Integer>> futures = planGoodsExtendThreadPool.invokeAll(callableList);
            for (Future<Integer> future : futures) {
                if (future.get() <= 0) {
                    connection.rollback();
                    return;
                }
            }
            //符合预期则手动提交
            connection.commit();
            System.out.println("添加完毕");
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            log.info("error", e);
            throw new RuntimeException("出现异常");
        }
    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值