springboot手动事务回滚的实现代码
亲测在使用@Transactional、@Transactional(rollbackFor = Exception.class)及catch异常之后 throw new RuntimeException();仍然不能解决线程中的事务回滚。下面使用线程所机制,进行整体的事务提交及事务回滚,代码如下:
在springboot启动类上加 @EnableTransactionManagement 注解
线程类中添加以下代码
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Autowired
private TransactionDefinition transactionDefinition;
private Lock lock = new ReentrantLock();
// todo 业务处理方法 数据存储异常 手动进行回滚
public void saveMsg(String message) throws Exception {
lock.lock();
TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
try {
//todo 具体业务,对数据库的操作 start
test1Service.save(test1);
test2Service.save(test2);
//end
platformTransactionManager.commit(transaction);
} catch (Exception e) {
platformTransactionManager.rollback(transaction);
e.printStackTrace();
} finally {
lock.unlock();
}
}
注:如果无法用 @Autowired 程序启动进行对象创建,可以使用init静态注入,如果对象可以正常创建,下面代码可以忽略。
@Autowired
private static PlatformTransactionManager platformTransactionManager;
@Autowired
private static TransactionDefinition transactionDefinition;
@Autowired
public void init(PlatformTransactionManager platformTransactionManager,TransactionDefinition transactionDefinition
) {
DriverAlfaServerHandler.platformTransactionManager = platformTransactionManager;
DriverAlfaServerHandler.transactionDefinition = transactionDefinition;
}
此回滚方法亲测有效。
到此这篇关于springboot手动事务回滚的实现代码的文章就介绍到这了,更多相关springboot 事务回滚内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
详细分析Java并发集合ArrayBlockingQueue的用法
这篇文章主要介绍了详细分析Java并发集合ArrayBlockingQueue的用法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-04-04
MyBatis-Plus QueryWrapper及LambdaQueryWrapper的使用详解
这篇文章主要介绍了MyBatis-Plus QueryWrapper及LambdaQueryWrapper的使用详解,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-03-03
解决@Transactional注解事务不回滚不起作用的问题
这篇文章主要介绍了解决@Transactional注解事务不回滚不起作用的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-02-02
Spring Cloud Ribbon实现客户端负载均衡的方法
本篇文章主要介绍了Spring Cloud Ribbon实现客户端负载均衡的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-05-05
关于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服务传输
这篇文章主要介绍了关于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服务传输的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-01-01
Java EasyExcel利用填充模版动态生成多个sheet页
这篇文章主要为大家详细介绍了Java EasyExcel如何利用填充模版动态生成多个sheet页,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下2023-12-12


最新评论