gpt4 book ai didi

Java/Spring : How to specify order for nested transactions with TransactionSynchronizationManager

转载 作者:太空宇宙 更新时间:2023-11-04 09:08:30 30 4
gpt4 key购买 nike

我有一些逻辑需要在事务提交后执行,所以我使用如下所示的内容:

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
//do work
}
});

这工作得很好。我的问题是,如果我在嵌套事务中注册多个像这样的处理程序,顺序是否保证在注册顺序中?例如:

class Obj1 {
@Transactional
public void doTX1() {
//invoke another method that is marked as transactional
obj2.doInnerTx();

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
System.out.println("Outer TX");
}
});
}
}

class Obj2 {
@Transactional
public void doInnerTx() {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
System.out.println("Inner TX");
}
});
}
}

输出:

Inner TX
Outer TX

但这能保证吗?如果不是,我将如何强制执行顺序,使内部始终首先执行?

最佳答案

registerSynchronization()方法的javadoc说:

Note that synchronizations can implement the
* {@link org.springframework.core.Ordered} interface.
* They will be executed in an order according to their order value (if any)

如果您使用 new TransactionSynchronizationAdapter() {..} 而不是 new TransactionSynchronization() {..},则可以重写 getOrder() 方法以及 afterCommit(),因为 TransactionSynchronizationAdapter 已经实现了 Ordered 接口(interface)。来自javadoc:

The default * {@link #getOrder() order} is 
{@link Ordered#LOWEST_PRECEDENCE}, indicating * late execution; return a lower
value for earlier execution.

最低优先级值为Integer.MAX_VALUE

关于Java/Spring : How to specify order for nested transactions with TransactionSynchronizationManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59935099/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com