您的位置:首页 > 文旅 > 旅游 > 【实战】Spring Boot 嵌套事务REQUIRES_NEW与NESTED在项目中的运用

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

2024/10/7 0:27:48 来源:https://blog.csdn.net/weixin_39970883/article/details/141604834  浏览:    关键词:【实战】Spring Boot 嵌套事务REQUIRES_NEW与NESTED在项目中的运用

文章目录

    • 引言
    • 1. 什么是Nested Transactions?
    • 2. Spring Boot中的事务管理
      • 2.1 基本用法
      • 2.2 Nested Transactions的需求场景
    • 3. 实现Nested Transactions
      • 3.1 使用Propagation.REQUIRED)/Propagation.NESTED)
      • 3.2 嵌套事务REQUIRES_NEW与NESTED
      • 3.3 注意事项
    • 4. 测试Nested Transactions
    • 5. 总结

在这里插入图片描述

引言

在开发基于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 {@Resourceprivate 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)@Overridepublic 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 {@Resourceprivate 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)@Overridepublic 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)@Overridepublic 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 {@Resourceprivate AccountService accountService;@Resourceprivate AccountMapper accountMapper;/*** testTransferNestedTransaction* @author senfel* @date 2024/8/27 15:36 * @return void*/@Testpublic 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则是会受到外部事务影响。所以,在实际的开发中我们也需要注意嵌套事务的局限性和潜在的性能问题,以确保应用程序的高效运行。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com