• Spring 事务失效的八种场景


    Spring 事务失效的八种场景

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

    代码如下:

    • Spring 默认只会回滚非检查异常,如果不进行配置,当发生检查异常时就不能正确回滚,例如下面不能正确找到文件的异常
    @Service
    public class Service1 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @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("aaa");
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 原因:Spring 默认只会回滚非检查异常

    • 解法:配置 rollbackFor 属性

      • @Transactional(rollbackFor = Exception.class)

    修改后代码如下:

    @Service
    public class Service1 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @Transactional(rollbackFor = Exception.class)
        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("aaa");
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2. 业务方法内自己 try-catch 异常导致事务不能正确回滚

    例如下面代码:

    • 即使添加@Transactional(rollbackFor = Exception.class)也不行,因为这个异常是在程序里被处理的,没有通知给事务,事务根本捕捉不到。
    @Service
    public class Service2 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @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("aaa");
                    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
    • 原因:事务通知只有捉到了目标抛出的异常,才能进行后续的回滚处理,如果目标自己处理掉异常,事务通知无法知悉

    • 解法1:异常原样抛出

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

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

    修改后代码如下:

    @Service
    public class Service2 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @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("aaa");
                    accountMapper.update(to, amount);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                // 1. 原样抛出,通知事务发生异常
                // throw new RuntimeException(e);
                // 2. 手动回滚事务
                TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

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

    业务层代码如下:

    @Service
    public class Service3 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @Transactional(rollbackFor = Exception.class)
        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("aaa");
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    切面类代码如下

    @Aspect
    public class MyAspect {
        @Around("execution(* transfer(..))")
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
            LoggerUtils.get().debug("log:{}", pjp.getTarget());
            try {
                return pjp.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 原因:事务切面优先级最低,但如果自定义的切面优先级和他一样,则还是自定义切面在内层,这时若自定义切面没有正确抛出异常,事务根本捕获不到
    • 解法1:异常原样抛出
      • 在 catch 块添加 throw new RuntimeException(e);
    • 解法2:手动设置 TransactionStatus.setRollbackOnly()
      • 在 catch 块添加 TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
    • 解法3:调整切面顺序,在 MyAspect 上添加 @Order(Ordered.LOWEST_PRECEDENCE - 1) (但是这样不推荐,可能会影响其他切点执行的的优先级)

    修改后代码如下:

    @Aspect
    public class MyAspect {
        @Around("execution(* transfer(..))")
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
            LoggerUtils.get().debug("log:{}", pjp.getTarget());
            try {
                return pjp.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
                return null;
                // 1. 原样抛出,通知事务发生异常
                // throw new RuntimeException(e);
                // 2. 手动回滚事务
                TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    4. 非 public 方法导致的事务失效

    代码如下所示:

    @Service
    public class Service4 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @Transactional
        void transfer(int from, int to, int amount) throws FileNotFoundException {
            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
    • 原因:Spring 为方法创建代理、添加事务通知、前提条件都是该方法是 public 的

    • 解法1:改为 public 方法

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

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

    5. 父子容器导致的事务失效

    代码如下所示:

    package com.yyl.tx.app.service;
    
    // ...
    
    @Service
    public class Service5 {
    
        @Autowired
        private AccountMapper accountMapper;
    
        @Transactional(rollbackFor = Exception.class)
        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);
                accountMapper.update(to, amount);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    控制器类

    package com.yyl.tx.app.controller;
    
    // ...
    
    @Controller
    public class AccountController {
    
        @Autowired
        public Service5 service;
    
        public void transfer(int from, int to, int amount) throws FileNotFoundException {
            service.transfer(from, to, amount);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    App 配置类

    @Configuration
    @ComponentScan("com.yyl.tx.app.service")
    @EnableTransactionManagement
    // ...
    public class AppConfig {
        // ... 有事务相关配置
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Web 配置类

    @Configuration
    @ComponentScan("com.yyl.tx.app")
    // ...
    public class WebConfig {
        // ... 无事务配置
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

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

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

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

      修改WebConfig 代码如下:

      @Configuration
      @ComponentScan("com.yyl.tx.app.controller")
      // ...
      public class WebConfig {
          // ... 无事务配置
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • 解法2:不要用父子容器,所有 bean 放在同一容器

    而典型的父子容器就是spring和springmvc同时使用的时候。分别ContextLoaderListener 创建的 容器是父容器,DispatcherServlet 创建的容器是子容器。

    而父容器和子容器的区别。比如父容器有a.b.c三个bean对象,子容器有d.e.f三个bean对象,子容器就可以通过getBean方法调用父容器的a.b.c bean对象,而父容器不能通过getBean拿到子容器的d.e.f三个bean对象。但是这里有一个例外property-placeholder,容器中读取的配置文件就是私有的,互相不能访问。其中也要弄清楚的是父子容器并不是一种包含关系,而是平行关系,但是在子容器中有一个parent,指向父容器,也就是说子容器在通过getBean访问父容器中的bean对象时是通过parent访问。

    这种做法的实际意思就是在一个JVM,只有一个树状结构的容器树。可以通过子容器访问父容器资源。就比如在实际开发中使用ssm框架,spring可以管理service,mapper,springmvc管理controller,mybatis编写mapper,controller就需要调用service,service调用mapper,因为springmvc容器是spring的子容器,可以通过父容器找到service和mapper,但是在service中却是找不到controller的。保证一种资源的局部性。

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

    代码如下:

    • 此时调用bar()方法,他没有经过任何代理,只是作为一个普通方法
    @Service
    public class Service6 {
    
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
        public void foo() throws FileNotFoundException {
            LoggerUtils.get().debug("foo");
            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
    • 原因:本类方法调用不经过代理,因此无法增强

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

    • 解法2:通过 AopContext 拿到代理对象,来调用

    • 解法3:通过 CTW,LTW 实现功能增强

    解法1

    @Service
    public class Service6 {
    
    	@Autowired
    	private Service6 proxy; // 本质上是一种循环依赖
    
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
        public void foo() throws FileNotFoundException {
            LoggerUtils.get().debug("foo");
    		System.out.println(proxy.getClass());
    		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
    • 17
    • 18

    解法2,还需要在 AppConfig 上添加 @EnableAspectJAutoProxy(exposeProxy = true)

    @Service
    public class Service6 {
        
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
        public void foo() throws FileNotFoundException {
            LoggerUtils.get().debug("foo");
            ((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
    • 14

    7. @Transactional 没有保证原子行为

    代码如下:

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

    @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
    • 原因:事务的原子性仅涵盖 insert、update、delete、select … for update 语句,select 方法并不阻塞

    image-20210903120436365

    • 如上图所示,红色线程和蓝色线程的查询都发生在扣减之前,都以为自己有足够的余额做扣减

    8. @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 块内
    • 可以参考下图发现,蓝色线程的查询只要在红色线程提交(commit)之前执行,那么依然会查询到有 1000 足够余额来转账

    image-20210903120800185

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

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

  • 相关阅读:
    何为量子计算机?
    实时配送跟踪功能的实现:外卖跑腿小程序的技术挑战
    【初阶数据结构】树结构与二叉树的基础概念
    30出头成为复旦博导,陈思明:敲代码和写诗,我两样都要
    使用flutter的Scaffold脚手架开发一个最简单的带tabbar的app模板
    正则表达式小计
    马斯克搞脑机得“开瓢”?MIT 早在研究「挂耳式耳机」,戴上=“把整个互联网装进脑子”!...
    基于AD Event日志检测LSASS凭证窃取攻击
    MySQL 慢查询日志 使用方法浅析 日志定位与优化技巧
    redis未授权漏洞
  • 原文地址:https://blog.csdn.net/weixin_45525272/article/details/126519848