亲测在使用@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; }
此回滚方法亲测有效。