[英]spring transaction timeout configurable
我有一個具有固定超時的事務方法。 有沒有辦法通過即application.yml
使事務超時可配置?
@Transactional(propagation = Propagation.REQUIRED, timeout = TIMEOUT)
public String doStuff(String id) throws Exception {
service.doSomeStuff
}
由於我們無法為 Java 注釋屬性分配變量值,要以編程方式設置@Transactional
的timeout
,最好的辦法是覆蓋AbstractPlatformTransactionManager#determineTimeout()
。
假設您正在使用JpaTransactionManager
,新的管理器看起來像下面的代碼。 它允許為每個事務設置超時。 我們可以使用TransactionDefinition
的名稱來標識一個事務,在 Spring 聲明式事務的情況下,默認名稱的格式為FullyQualifiedClassName.MethodName
。
public class FooTransactionManager extends JpaTransactionManager {
private Map<String, Integer> txTimeout = new HashMap<String, Integer>();
public <T> void configureTxTimeout(Class<T> clazz, String methodName, Integer timeoutSecond) {
txTimeout.put(clazz.getName() + "." + methodName, timeoutSecond);
}
//The timeout set by `configureTxTimeout` will have higher priority than the one set in @Transactional
@Override
protected int determineTimeout(TransactionDefinition definition) {;
if (txTimeout.containsKey(definition.getName())) {
return txTimeout.get(definition.getName());
} else {
return super.determineTimeout(definition);
}
}
}
然后配置PlatformTransactionManager
:
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final FooTransactionManager transactionManager = new FooTransactionManager();
transactionManager.setEntityManagerFactory(emf);
transactionManager.configureTxTimeout(Foo.class, "doStuff", 10);
transactionManager.configureTxTimeout(Bar.class, "doStuff", 20);
transactionManager.configureTxTimeout(Bar.class, "doMoreStuff", 30);
//blablabla
return transactionManager;
}
以上代碼僅用於演示目的。 實際上,您可以在配置期間使用@Value
從外部屬性(例如application.yml
)中讀取值。
2020 年 6 月 25 日更新:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.