@Transactional(isolation = Isolation.SERIALIZABLE)我在spring项目中的几个方法上都有这个注解。如果由于“序列化访问问题”而出现异常,如果我想重试特定的事务,最好的方法是什么?有注解@Retryable,但对我来说,如何使用它并不是很简单,这样事务将回滚,然后只对特定异常重试,而对其他运行时异常只进行回滚。提前谢谢。
发布于 2018-03-03 08:54:53
一个简单的解决方案是有一个方法,它是执行逻辑的“入口点”;它将实际的逻辑委托给事务方法。通常,这样做的一个好方法是让一个类具有事务性注释并完成工作,另一个类是客户端与委托交互的接口;提供一种间接的形式。
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) {
...
}请注意,您可能会在从同一类中的不同方法调用事务性方法(即调用this.doTransactionalMethod())时遇到问题,因此事务性方法的调用是通过Spring Application上下文进行的。这是由于Spring AOP包装类以使用事务语义的方式造成的。请参阅:Spring @Transaction method call by the method within the same class, does not work?
https://stackoverflow.com/questions/49032273
复制相似问题