• SpringBoot事务失效场景、事务正确使用姿势


    抛出检查异常导致事务不能正确回滚

    @Service
    public class Service1 {
    
         /**
          模拟转账事务
         */
         
        @Autowired
        private AccountMapper accountMapper;
        
        /**
        from //转账人
        to //收款人
        amount //转账金额
        */
        @Transactional
        public void transfer(int from, int to, int amount) throws FileNotFoundException {
            int fromBalance = accountMapper.findBalanceBy(from);
            if (fromBalance - amount >= 0) {
                accountMapper.update(from, -1 * amount);
                new FileInputStream("XXX");//制造文件找不到异常,方法上抛出此异常
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 原因:Spring 默认只会回滚非检查异常

    • 解法:配置 rollbackFor 属性

      • @Transactional(rollbackFor = Exception.class)

    try-catch 异常导致事务不能正确回滚

    @Service
    public class Service2 {
          /**
          模拟转账事务
         */
    
        @Autowired
        private AccountMapper accountMapper;
    
         /**
        from //转账人
        to //收款人
        amount //转账金额
        */
        @Transactional(rollbackFor = Exception.class)
        public void transfer(int from, int to, int amount)  {
            try {
                int fromBalance = accountMapper.findBalanceBy(from);
                if (fromBalance - amount >= 0) {
                    accountMapper.update(from, -1 * amount);
                    new FileInputStream("XXX");//制造文件找不到异常,并用catch块处理异常
                    accountMapper.update(to, amount);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 原因:事务通知只有捉到了目标抛出的异常,才能进行后续的回滚处理,如果目标自己处理掉异常,事务通知无法知悉

    • 解法1:异常原样抛出

      • 在 catch 块添加 throw new RuntimeException(e);
    • 解法2:手动设置 TransactionStatus.setRollbackOnly()

      • 在 catch 块添加 TransactionInterceptor.currentTransactionStatus().setRollbackOnly();

    aop 切面顺序导致导致事务不能正确回滚

    @Service
    public class Service3 {
    
         /**
          模拟转账事务
         */
         
        @Autowired
        private AccountMapper accountMapper;
        
        /**
        from //转账人
        to //收款人
        amount //转账金额
        */
        @Transactional
        public void transfer(int from, int to, int amount) throws FileNotFoundException {
            int fromBalance = accountMapper.findBalanceBy(from);
            if (fromBalance - amount >= 0) {
                accountMapper.update(from, -1 * amount);
                new FileInputStream("XXX");//制造文件找不到异常,方法上抛出此异常
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    @Aspect//切面类
    public class MyAspect {
        @Around("execution(* transfer(..))")
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
            try {
                return pjp.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 原因:事务切面优先级最低,但如果自定义的切面优先级和他一样,则还是自定义切面在内层,这时若自定义切面没有正确抛出异常…

    • 解法1:异常原样抛出

      • 在 catch 块添加 throw new RuntimeException(e);
    • 解法2:手动设置 TransactionStatus.setRollbackOnly()

      • 在 catch 块添加 TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
    • 解法3:调整切面顺序,在 MyAspect 上添加 @Order(Ordered.LOWEST_PRECEDENCE - 1) (不推荐)

    非 public 方法导致的事务失效

    @Service
    public class Service4 {
    
         /**
          模拟转账事务
         */
         
        @Autowired
        private AccountMapper accountMapper;
        
        /**
        from //转账人
        to //收款人
        amount //转账金额
        */
        @Transactional
        void transfer(int from, int to, int amount) {
            int fromBalance = accountMapper.findBalanceBy(from);
            if (fromBalance - amount >= 0) {
                accountMapper.update(from, -1 * amount);
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 原因:Spring 为方法创建代理、添加事务通知、前提条件都是该方法是 public 的

    • 解法1:改为 public 方法

    • 解法2:添加 bean 配置如下(不推荐)

    @Bean
    public TransactionAttributeSource transactionAttributeSource() {
        return new AnnotationTransactionAttributeSource(false);//默认是public
    }
    
    • 1
    • 2
    • 3
    • 4

    父子容器导致的事务失效

    package tx.app.service;
    
    // ...
    
    @Service
    public class Service5 {
          /**
          模拟转账事务
         */
        @Autowired
        private AccountMapper accountMapper;
         
         /**
        from //转账人
        to //收款人
        amount //转账金额
        */
        @Transactional(rollbackFor = Exception.class)
        public void transfer(int from, int to, int amount) {
            int fromBalance = accountMapper.findBalanceBy(from);
            if (fromBalance - amount >= 0) {
                accountMapper.update(from, -1 * amount);
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    package tx.app.controller;
    
    // ...
    
    @Controller
    public class AccountController {
    
        @Autowired
        public Service5 service;
    
        public void transfer(int from, int to, int amount)  {
            service.transfer(from, to, amount);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    //App 配置类
    @Configuration
    @ComponentScan("tx.app.service")
    @EnableTransactionManagement
    // ...
    public class AppConfig {
        // ... 有事务相关配置
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    //Web 配置类
    @Configuration
    @ComponentScan("tx.app")
    // ...
    public class WebConfig {
        // ... 无事务配置
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    现在配置了父子容器,WebConfig 对应子容器AppConfig 对应父容器,发现事务依然失效

    • 原因:子容器扫描范围过大,把未加事务配置的 service 扫描进来

    • 解法1:各扫描各的,不要图简便

    • 解法2:不要用父子容器,所有 bean 放在同一容器

    调用本类方法导致传播行为失效

    @Service
    public class Service6 {
    
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
        public void foo() throws FileNotFoundException {
            bar();
        }
    
        @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
        public void bar() throws FileNotFoundException {
            LoggerUtils.get().debug("bar");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 原因:本类方法调用不经过代理,因此无法增强

    • 解法1:依赖注入自己(代理)来调用

    @Service
    public class Service6 {
    
    	@Autowired
    	private Service6 proxy; // 本质上是一种循环依赖
    
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
        public void foo() throws FileNotFoundException {
    		proxy.bar();
        }
    
        @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
        public void bar() throws FileNotFoundException {
            LoggerUtils.get().debug("bar");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 解法2:通过 AopContext 拿到代理对象来调用,在 AppConfig 上添加 @EnableAspectJAutoProxy(exposeProxy = true)
    @Service
    public class Service6 {
        
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
        public void foo() throws FileNotFoundException {
            ((Service6) AopContext.currentProxy()).bar();
        }
    
        @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
        public void bar() throws FileNotFoundException {
            LoggerUtils.get().debug("bar");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    @Transactional 没有保证原子行为

    @Service
    public class Service7 {
    
        private static final Logger logger = LoggerFactory.getLogger(Service7.class);
    
        @Autowired
        private AccountMapper accountMapper;
    
        @Transactional(rollbackFor = Exception.class)
        public void transfer(int from, int to, int amount) {
            int fromBalance = accountMapper.findBalanceBy(from);
            logger.debug("更新前查询余额为: {}", fromBalance);
            if (fromBalance - amount >= 0) {
                accountMapper.update(from, -1 * amount);
                accountMapper.update(to, amount);
            }
        }
    
        public int findBalance(int accountNo) {
            return accountMapper.findBalanceBy(accountNo);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    上面的代码实际上是有 bug 的,假设 from 余额为 1000,两个线程都来转账 1000,可能会出现扣减为负数的情况。

    • 原因:事务的原子性仅涵盖 insert、update、delete、select … for update 语句,select 方法并不阻塞

    @Transactional 方法导致的 synchronized 失效

    针对上面的问题,能否在方法上加 synchronized 锁来解决呢?

    @Service
    public class Service7 {
    
        private static final Logger logger = LoggerFactory.getLogger(Service7.class);
    
        @Autowired
        private AccountMapper accountMapper;
    
        @Transactional(rollbackFor = Exception.class)
        public synchronized void transfer(int from, int to, int amount) {
            int fromBalance = accountMapper.findBalanceBy(from);
            logger.debug("更新前查询余额为: {}", fromBalance);
            if (fromBalance - amount >= 0) {
                accountMapper.update(from, -1 * amount);
                accountMapper.update(to, amount);
            }
        }
    
        public int findBalance(int accountNo) {
            return accountMapper.findBalanceBy(accountNo);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    结果是不行,原因如下

    • synchronized 保证的仅是目标方法的原子性,环绕目标方法的还有 commit 等操作,它们并未处于 sync 块内

    • 解法1:synchronized 范围应扩大至代理方法调用

    • 解法2:使用 select … for update 替换 select

  • 相关阅读:
    LeGO-LOAM
    浅析Java设计模式【2.2】——适配器
    算法平台中的题目模块
    SpringBoot教程(16) 什么是RESTful?
    pnpm和yarn2 pnp的对比
    运算符+事件三要素
    adb 连接 Android 手机(Wi-Fi版)
    FusionAD:用于自动驾驶预测和规划任务的多模态融合
    QAnything安装纪要
    23、JAVA进阶——日期操作类
  • 原文地址:https://blog.csdn.net/qq_54429571/article/details/126814655