TransactionSynchronization

TransactionSynchronization

是否有任何方法可以获取当前交易ID,对其进行存储/传递并在应用程序的另一部分中检查其状态?

例如:

@Service
public class Service {
    ...
    @Transactional(rollbackFor = Exception.class)
    public void performAction(Action action) {
        // start action
        String transactionId = ???     // getting current transaction id
        messenger.send(transactionId); // sending transaction id to consumer
        // continue action
    } <- commit transaction
}

public class Consumer {
    ...
    public void onRecieveMessage(String transactionId) {
        TransactionStatus ts = ??? // getting transaction from pool by id
        if (ts.isCompleted()) {
            // some actions
        } else {
            // wating or Future<?> or something else...
        }
    }
}


(实际上,问题是Consumer.onRecieveMessage在操作的事务完成之前执行,并且数据状态较旧)

最佳答案

我不知道通过其ID获取特定交易的任何方式(希望有人这样做)。

我要做的是实现一个TransactionSynchronization实例,该实例拥有您要跟踪的一种值:

public class YourTransactionTracker extends TransactionSynchronizationAdapter {

    private Value value;

    public YourTransactionTracker(Value value) {
        this.value = value;
    }

    @Override
    public void afterCompletion(int status) {
        //transaction handling your 'value' has been completed with the status 'status'
        //do whatever you want here
    }

    //you can also override other methods like beforeCompletion(), flush(), etc...
    //have a look at TransactionSynchronizationAdapter
}


TransactionSynchronizationAdapter只是TransactionSynchronization具有空方法的实现。

然后,您可以使用TransactionSynchronization实例在事务中挂接一个回调,该回调将在事务生命周期的不同阶段进行调用。

您可以使用TransactionSynchronizationManager在Spring中执行此操作:

    TransactionSynchronizationManager.registerSynchronization(
             new YourTransactionTracker(theValueYouAreTracking);

10-07 15:55