【实战】Spring Boot 嵌套事务REQUIRES_NEW与NESTED在项目中的运用

24 篇文章 3 订阅
17 篇文章 1 订阅


在这里插入图片描述

引言

在开发基于Spring Boot的应用程序时,事务管理是一项至关重要的任务。事务确保了数据的一致性和完整性,尤其是在执行一系列数据库操作时。当涉及到复杂的业务逻辑时,可能需要在单个事务中嵌套多个事务,即所谓的“Nested Transactions”。本文将深入探讨如何在Spring Boot项目中实现和管理Nested Transactions,并深入讨论REQUIRES_NEW与NESTED在项目中的运用。

1. 什么是Nested Transactions?

Nested Transactions指的是在一个外部事务中嵌套一个或多个内部事务。这种模式通常用于处理复杂的业务逻辑,其中某些部分需要在更细粒度上进行控制。例如,在一个转账操作中,可能需要先检查账户余额是否足够,然后再执行实际的转账操作。如果在这个过程中出现了任何错误,如余额不足,那么整个操作应该回滚,以保证数据的一致性。

2. Spring Boot中的事务管理

在Spring Boot中,事务管理主要通过@Transactional注解来实现。这个注解可以添加到类或方法级别,以指定事务的边界。Spring Boot还提供了TransactionManager接口,它负责事务的开始、提交和回滚。

2.1 基本用法

下面是一个简单的例子,展示了如何在Spring Boot中使用@Transactional注解:

/**
 * AccountServiceImpl
 * @author senfel
 * @version 1.0
 * @date 2024/8/27 14:30
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;
    /**
     * 转账
     * @param fromAccount
     * @param toAccount
     * @param amount
     * @author senfel
     * @date 2024/8/27 14:36
     * @return void
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void transfer(Long fromAccount, Long toAccount, BigDecimal amount) {
        Account from = accountMapper.selectById(fromAccount);
        Account to = accountMapper.selectById(toAccount);
        from.setBalance(from.getBalance().subtract(amount));
        to.setBalance(to.getBalance().add(amount));
        accountMapper.updateById(from);
        accountMapper.updateById(to);
    }
}

2.2 Nested Transactions的需求场景

在某些情况下,我们可能希望在转账的过程中加入一些额的步骤,就需要使用Nested Transactions来实现更细粒度的控制。

3. 实现Nested Transactions

3.1 使用Propagation.REQUIRED)/Propagation.NESTED)

默认情况下,@Transactional注解使用Propagation.REQUIRED传播行为。这意味着如果当前没有事务,就创建一个新的事务;如果已经存在一个事务,则加入到这个事务中;Propagation.NESTED则是开启一个当前事务的嵌套事务。但是,这并不能实现Nested Transactions。

3.2 嵌套事务REQUIRES_NEW与NESTED

使用@Transactional(propagation = Propagation.REQUIRES_NEW)
会强制在当前事务中创建一个新的事务,这个事务不影响外部事务,不受外部事务约束;
使用@Transactional(propagation = Propagation.NESTED)
会强制在当前事务中开启一个嵌套事务,这个事务生命周期依赖于外部事务,不影响外部事务,但受外部事务约束。
示例代码:

/**
 * AccountServiceImpl
 * @author senfel
 * @version 1.0
 * @date 2024/8/27 14:30
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;
    /**
     * transferByNew
     * @param fromAccount
     * @param toAccount
     * @param amount
     * @author senfel
     * @date 2024/8/27 14:36
     * @return void
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void transferByNew(Long fromAccount, Long toAccount, BigDecimal amount) {
        Account acc = accountMapper.selectById(fromAccount);
        if(acc.getBalance().compareTo(amount) < 0){
            throw new RuntimeException("转出账户余额不足");
        }
        //从service层获取bean调用方法开启事务,否则本类嵌套事务开启无效
        AccountServiceImpl bean = SpringUtil.getBean(AccountServiceImpl.class);
        bean.doTransferByNew(fromAccount, toAccount, amount);
        if(amount.compareTo(new BigDecimal("100")) == 0){
            //手动模拟异常
            throw new RuntimeException("转账金额不能为100");
        }
    }

    /**
     * transferByNested
     * @param fromAccount
     * @param toAccount
     * @param amount
     * @author senfel
     * @date 2024/8/27 15:19
     * @return void
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void transferByNested(Long fromAccount, Long toAccount, BigDecimal amount) {
        Account acc = accountMapper.selectById(fromAccount);
        if(acc.getBalance().compareTo(amount) < 0){
            throw new RuntimeException("转出账户余额不足");
        }
        //从service层获取bean调用方法开启事务,否则本类嵌套事务开启无效
        AccountServiceImpl bean = SpringUtil.getBean(AccountServiceImpl.class);
        bean.doTransferByNested(fromAccount, toAccount, amount);
        if(amount.compareTo(new BigDecimal("100")) == 0){
            //手动模拟异常
            throw new RuntimeException("转账金额不能为100");
        }
    }


    /**
     * doTransferByNested嵌套事务
     * @param fromAccount
     * @param toAccount
     * @param amount
     * @author senfel
     * @date 2024/8/27 14:42 
     * @return void
     */
    @Transactional(propagation = Propagation.NESTED)
    public void doTransferByNested(Long fromAccount, Long toAccount, BigDecimal amount) {
        Account from = accountMapper.selectById(fromAccount);
        Account to = accountMapper.selectById(toAccount);
        from.setBalance(from.getBalance().subtract(amount));
        to.setBalance(to.getBalance().add(amount));
        accountMapper.updateById(from);
        accountMapper.updateById(to);
    }

    /**
     * doTransferByNew开启一个新事物
     * @param fromAccount
     * @param toAccount
     * @param amount
     * @author senfel
     * @date 2024/8/27 15:15
     * @return void
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void doTransferByNew(Long fromAccount, Long toAccount, BigDecimal amount) {
        Account from = accountMapper.selectById(fromAccount);
        Account to = accountMapper.selectById(toAccount);
        from.setBalance(from.getBalance().subtract(amount));
        to.setBalance(to.getBalance().add(amount));
        accountMapper.updateById(from);
        accountMapper.updateById(to);
    }
}

3.3 注意事项

嵌套事务的隔离性:REQUIRES_NEW不会受到外部事务的影响,但NESTED会受到外部事务影响。
回滚行为:如果嵌套事务失败并回滚,它不会影响外部事务的状态,前提是嵌套方法被catch住。
性能考虑:频繁地开启和关闭事务可能会导致性能下降。因此,在设计时应尽量减少嵌套事务的使用。

4. 测试Nested Transactions

为了验证Nested Transactions的正确性,我们可以编写单元测试来模拟不同的场景。
示例测试代码:

/**
 * NestedTransactionTest
 * @author senfel
 * @version 1.0
 * @date 2024/8/27 14:49
 */
@SpringBootTest
public class NestedTransactionTest {

    @Resource
    private AccountService accountService;
    @Resource
    private AccountMapper accountMapper;

    /**
     * testTransferNestedTransaction
     * @author senfel
     * @date 2024/8/27 15:36 
     * @return void
     */
    @Test
    public void testTransferNestedTransaction() {
        Long fromAccount = 1L;
        Long toAccount = 2L;
        BigDecimal amount = new BigDecimal("100");

        Account a1 = new Account(fromAccount, "A1",new BigDecimal("500"));
        Account b1 = new Account(toAccount,"B2", BigDecimal.ZERO);
        accountMapper.insert(a1);
        accountMapper.insert(b1);
        System.err.println("==========嵌套事务初始数据==============");
        System.err.println(JSONObject.toJSONString(a1));
        System.err.println(JSONObject.toJSONString(b1));
        System.err.println("==========嵌套事务REQUIRES_NEW==============");
        // 嵌套事务REQUIRES_NEW 测试
        try {
            accountService.transferByNew(fromAccount, toAccount, amount);
        }catch (Exception e){
            e.printStackTrace();
        }
        // 验证 嵌套事务REQUIRES_NEW 外部报错嵌套事务提交成功
        Account a2 = accountMapper.selectById(fromAccount);
        Account b2 = accountMapper.selectById(toAccount);
        System.err.println(JSONObject.toJSONString(a2));
        System.err.println(JSONObject.toJSONString(b2));

        System.err.println("==========嵌套事务NESTED==============");
        // 嵌套事务NESTED 测试
        try {
            accountService.transferByNested(fromAccount, toAccount, amount);
        }catch (Exception e){
            e.printStackTrace();
        }
        // 验证 嵌套事务NESTED 外部报错嵌套事务提交失败
        Account a3 = accountMapper.selectById(fromAccount);
        Account b3 = accountMapper.selectById(toAccount);
        System.err.println(JSONObject.toJSONString(a3));
        System.err.println(JSONObject.toJSONString(b3));
    }
}

执行结果:

嵌套事务初始数据====
{“balance”:500,“id”:1,“name”:“A1”}
{“balance”:0,“id”:2,“name”:“B2”}
嵌套事务REQUIRES_NEW====
{“balance”:400.00,“id”:1,“name”:“A1”}
{“balance”:100.00,“id”:2,“name”:“B2”}
嵌套事务NESTED====
{“balance”:400.00,“id”:1,“name”:“A1”}
{“balance”:100.00,“id”:2,“name”:“B2”}

5. 总结

Nested Transactions是Spring Boot中一项非常有用的功能,它可以帮助我们在复杂业务逻辑中实现更细粒度的控制。通过使用REQUIRES_NEW或者NESTED,我们可以轻松地在现有事务中创建新的事务传播机制,其中REQUIRES_NEW不受外部事务影响,NESTED则是会受到外部事务影响。所以,在实际的开发中我们也需要注意嵌套事务的局限性和潜在的性能问题,以确保应用程序的高效运行。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小沈同学呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值