@Transactional(isolation = Isolation.SERIALIZABLE)重试机制

问题描述 投票:2回答:1
 @Transactional(isolation = Isolation.SERIALIZABLE)

我在我的spring项目中有几个方法的注释。如果由于“序列化访问问题”而存在异常,那么如果我想重试特定事务,最佳方法是什么。有一个注释@Retryable但是对我来说如何使用它并不是非常简单,因此事务将回滚然后仅针对该特定异常重试,并且仅针对其他运行时异常进行回滚。提前致谢。

java spring hibernate spring-boot transactional
1个回答
1
投票

一个简单的解决方案是使用一个方法作为执行逻辑的“切入点”;它将实际逻辑委托给事务方法。通常,这样做的一个好方法是让一个具有Transactional注释并且完成工作的类,另一个类是客户端与该代理交互的接口;提供一种间接的形式。

private static final int MAX_RETRY = 5;
public void doWork(T... parameters) {
    doWork(0, parameters);
}

private void doWork(int retryLevel, T... parameters) {
    if (retryLevel == MAX_RETRY) {
        throw new MaximumRetryCountException(); //or any other exception
    } else {
        try {
           //Get your Spring context through whatever method you usually use
           AppContext().getInstance().getBean(classInterestedIn.class).doTransactionalMethod(parameters);
        } catch (ExceptionToRetryFor e) {
            doWork((retryLevel + 1), parameters);
        }
    }
}

@Transactional(isolation = Isolation.SERIALIZABLE)
public void doTransactionalMethod(parameters) {
    ...
}

请注意,您可能会遇到从同一个类中的不同方法调用Transactional方法的问题(即调用this.doTransactionalMethod()),因此Transactional方法的调用是通过Spring Application Context调用的。这是由于Spring AOP包装类以使用事务语义的方式。见:Spring @Transaction method call by the method within the same class, does not work?

© www.soinside.com 2019 - 2024. All rights reserved.