解决springboot中的大事务问题:改用编程式事务

1.问题:原方法中有很多不需要进行事务控制的方法,一旦使用了事务注解会导致接口超时,高并发情况下数据库连接池消耗过大,回滚时间过长等问题
    @Transactional
    public void bigTransactional(){
        adminMapper.selectById(1);
        adminMapper.selectById(2);
        adminMapper.selectById(3);
        adminMapper.selectById(4);
        adminMapper.add(new Admin());
    }

以上方法是基于声明式注解实现的事务,很明显的是前面几个select语句是不需要事务管控的。为了优化这个方法,我们可以把声明式事务改为编程式事务

    @Autowired
    private TransactionTemplate transactionTemplate;
    
    public void bigTransactional(){
        adminMapper.selectById(1);
        adminMapper.selectById(2);
        adminMapper.selectById(3);
        adminMapper.selectById(4);
        transactionTemplate.execute(status->{
            adminMapper.add(new Admin());
            return true;
        });
    }

编程式事务相比声明式事务有哪些好处

1.更细粒度的控制,上述示例就体现了这个观点,代码块级的事务处理,提高了事务的灵活度

2.性能优化,声明式事务通过AOP实现,会引入一些额外的性能开销,而编程式事务直接调用事务管理API,在高并发的场景下性能会更好

posted @ 2024-11-05 20:52  天启A  阅读(60)  评论(0)    收藏  举报