Spring 事务回调

package com.example.demo.util;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class TransactionUtils {

    public static void doAfterTransaction(DoTrabsactionCompletion doTrabsactionCompletion){
        TransactionSynchronizationManager.registerSynchronization(doTrabsactionCompletion);
    }
    
    @Transactional
    public void doTx(){
        // start tx
        
        TransactionUtils.doAfterTransaction(new DoTrabsactionCompletion(()->{
            // sen MQ... RPC...
        }));
    }
}

class DoTrabsactionCompletion implements TransactionSynchronization {

    private Runnable runnable;

    public DoTrabsactionCompletion(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void afterCompletion(int status) {
        if (status == TransactionSynchronization.STATUS_COMMITTED){
            this.runnable.run();
        }
    }
}


参考博客

Spring 事务扩展机制 TransactionSynchronization

你可能感兴趣的:(Java,基础,java)