使用事务的 Spring 重试
Spring Retry 是否保证与 Spring 的 @Transactional
注释一起使用?
Is Spring Retry guaranteed to work with Spring's @Transactional
annotation?
具体来说,我正在尝试使用 @Retryable
进行乐观锁定.似乎它取决于创建的 AOP 代理的顺序.例如,如果调用如下所示:
Specifically, I'm trying to use @Retryable
for optimistic locking. It seems like it would be dependent on the ordering of the AOP proxies that were created. For example, if the calls look like this:
调用代码 -> 重试代理 -> 事务代理 -> 实际数据库代码
Calling code -> Retry Proxy -> Transaction Proxy -> Actual DB Code
那么它会正常工作,但如果代理的结构如下:
Then it would work correctly, but if the proxies were structured like this:
调用代码 -> 事务代理 -> 重试代理 -> 实际数据库代码
Calling code -> Transaction Proxy -> Retry Proxy -> Actual DB Code
然后重试将不起作用,因为关闭事务的行为是引发光学锁定异常的原因.
Then the retry wouldn't work, because the act of closing the transaction is what throws the optmistic locking exception.
在测试中,它似乎生成了第一个案例(重试,然后是事务),但我不知道这是有保证的行为还是只是幸运.
In testing, it appeared to generate the first case (retry, then transaction), but I couldn't tell if this was a guaranteed behavior or just lucky.
推荐答案
在这里找到答案:https://docs.spring.io/spring/docs/5.0.6.BUILD-SNAPSHOT/spring-framework-reference/data-access.html#transaction-declarative-annotations表 2 表明 Transactional
注释的通知具有 Ordered.LOWEST_PRECEDENCE
的顺序,这意味着将 Retryable
与 Transactional
只要您没有覆盖这些注释中的任何一个的建议顺序.换句话说,您可以安全地使用这种形式:
Found the answer here:
https://docs.spring.io/spring/docs/5.0.6.BUILD-SNAPSHOT/spring-framework-reference/data-access.html#transaction-declarative-annotations
Table 2 indicates that the advice for the Transactional
annotation has an order of Ordered.LOWEST_PRECEDENCE
, which means that it is safe to combine Retryable
with Transactional
as long as you aren't overriding the order of the advice for either of those annotations. In other words, you can safely use this form:
@Retryable(StaleStateException.class)
@Transactional
public void performDatabaseActions() {
//Database updates here that may cause an optimistic locking failure
//when the transaction closes
}
相关文章