有没有办法获取当前的交易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执行的时间早于动作的事务结束,数据状态是旧的)
答案 0 :(得分:0)
我不知道通过其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
:
TransactionSynchronizationManager.registerSynchronization(
new YourTransactionTracker(theValueYouAreTracking);