springboot 事务Transactional使用小技巧
使用场景:
我们在处理业务时会有这样的需求:我们需要在业务中需要调用远程的RPC接口,或者调用MQ发送消息,如果一切正常那自然皆大欢喜;但是,业务中出现了异常,导致了事务回滚,但是调用远程的RPC接口,或者调用MQ的动作是无法取消的,这可能就会出现严重的问题。
解决:在事务提交后调用接口
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author wjj
*/
public class TransactionUtils {
public static void doAfterTransaction(DoTransactionCompletion doTransactionCompletion) {
if (TransactionSynchronizationManager.isActualTransactionActive()){
TransactionSynchronizationManager.registerSynchronization(doTransactionCompletion);
}
}
@Transactional
public void aa(){
TransactionUtils.doAfterTransaction(new DoTransactionCompletion(()->{
//send MQ ... RPC
}));
}
}
class DoTransactionCompletion implements TransactionSynchronization {
private Runnable runnable;
public DoTransactionCompletion(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void afterCompletion(int status) {
if (status ==TransactionSynchronization.STATUS_COMMITTED){
this.runnable.run();
}
}
}
标签:TransactionSynchronizationManager,runnable,DoTransactionCompletion,springboot,Tr
From: https://www.cnblogs.com/WangJingjun/p/16895847.html