多线程事务回滚

地址:https://blog.csdn.net/zhangleiyes123/article/details/128628292

@Service
@Slf4j
public class UserPoService {

    private final static ExecutorService service = Executors.newFixedThreadPool(8);
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    public void saveThread(List<UserPO> userPoList) throws Exception {
        SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
        // 获取数据库连接,获取会话(内部自有事务)
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Connection connection = sqlSession.getConnection();
        try {
            // 设置手动提交
            connection.setAutoCommit(false);
            // 获取mapper
            UserMapper employeeMapper = sqlSession.getMapper(UserMapper.class);
            // 先做删除操作
            employeeMapper.delete(null);
            // 获取执行器
            List<Callable<Integer>> callableList  = new ArrayList<>();

            AtomicBoolean atomicBoolean = new AtomicBoolean(true);
            for (int i =0; i < userPoList.size(); i++){
                if (i == userPoList.size() - 1){
                    atomicBoolean.set(false);
                }
                //使用返回结果的callable去执行,
                int finalI = i;
                Callable<Integer> callable = () -> {
                    //让最后一个线程抛出异常
                    if (!atomicBoolean.get()){
                        throw new Exception("001,出现异常");
                    }
                    return employeeMapper.insert(userPoList.get(finalI));
                };
                callableList.add(callable);
            }
            //执行子线程
            List<Future<Integer>> futures = service.invokeAll(callableList);
            for (Future<Integer> future : futures) {
                //如果有一个执行不成功,则全部回滚
                if (future.get() <= 0){
                    connection.rollback();
                    return;
                }
            }
            connection.commit();
            System.out.println("添加完毕");
        }catch (Exception e){
            connection.rollback();
            log.error("error",e);
            throw new Exception("002, 出现异常");
        }finally {
            connection.close();
        }
    }

}

 

 

@SpringBootTest
@RunWith(SpringRunner.class)
public class ThreadTest01 {
 
    @Resource
    private UserPoService userPoService;
 
    @Test
    public void MoreThreadTest2() {
        List<UserPO> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new UserPO().setUserName("user"+i).setPassword("111111"));
        }
        try {
            userPoService.saveThread(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

posted @ 2024-11-14 17:21  真某人  阅读(2)  评论(0编辑  收藏  举报