是否可以使用@Transactional测量所有Spring托管交易的时间? [英] Is it possible to measure time of all Spring managed transactions with @Transactional?
问题描述
我想测量Spring管理的交易时间,用 JpaTJpaTransactionManager
/ PlatformTransactionManager
来检测长待处理交易和警告一些听众关于这种情况。
I would like to measure time of transacactions managed by Spring with JpaTJpaTransactionManager
/PlatformTransactionManager
to detect long pending transactions and warn some listener about that condition.
我可以在 @Transactional
方法上使用方面,但由于交易传播,它不是检测确切事务何时开始或结束的好方法。
I could use aspect on @Transactional
methods but due to transaction propagation it's not a good way to detect when exact transaction is started or finished.
对于像事务监听器这样的东西,可以访问启动/结束事件以及一些bean名称对象启动trasaction或只是一个堆栈跟踪
It would be good to something like transaction listener with access to start/finish events together with some bean name of object starting the trasaction or just a stack trace
推荐答案
在带注释的方法中使用TransactionSynchronizationManager:
Use TransactionSynchronizationManager inside annotated method:
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
long startTime;
void beforeCommit() {
startTime = System.nanoTime();
}
void afterCommit(){
System.out.println("Transaction time: " + (System.nanoTime() - startTime));
}
});
跟踪方面的所有交易:
@Aspect
class TransactionAspect extends TransactionSynchronizationAdapter {
@Before("@annotation(org.springframework.transaction.annotation.Transactional)")
public void registerTransactionSyncrhonization() {
TransactionSynchronizationManager.registerSynchronization(this);
}
ThreadLocal<Long> startTime = new ThreadLocal<>();
void beforeCommit() {
startTime.set(System.nanoTime());
}
void afterCommit(){
System.out.println("Transaction time: " + (System.nanoTime() - startTime.get()));
}
}
这篇关于是否可以使用@Transactional测量所有Spring托管交易的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!