Spring乐观锁定:如何重试事务方法直到提交成功

kna*_*983 19 java spring transactions aspectj optimistic-locking

我使用Spring 2.5和Hibernate JPA实现Java和"容器"管理事务.

我有一个"用户提交后"方法,它在后台更新数据,无论是异常ConcurrencyFailureException还是StaleObjectStateException异常都需要提交,因为它永远不会显示给客户端.换句话说,需要将乐观锁定变为悲观.(如果方法执行需要更长的时间并且有人在其他事务中更改了数据,则可能发生)


我读了很多关于幂等的东西,如果异常搜索DEFAULT_MAX_RETRIES6.2.7则重试.示例第14.5章.重试.我也在这里这里找到了stackoverflow .

我试过这个:

public aspect RetryOnConcurrencyExceptionAspect {

    private static final int DEFAULT_MAX_RETRIES = 20;
    private int maxRetries = DEFAULT_MAX_RETRIES;

    Object around(): execution( * * (..) ) && @annotation(RetryOnConcurrencyException) && @annotation(Transactional) {

        int numAttempts = 0;
          RuntimeException failureException = null;
          do {
                numAttempts++;
                try {
                    return proceed(); 
                } 
                catch( OptimisticLockingFailureException ex ) {
                    failureException = ex;
                }
                catch(ConcurrencyFailureException ex) {
                    failureException = ex;
                }
                catch( StaleObjectStateException ex) {
                    failureException = ex;
                }
          } while( numAttempts <= this.maxRetries );
          throw failureException;

    }
}
Run Code Online (Sandbox Code Playgroud)

RetryOnConcurrencyException如果发生异常,则是我的注释,用于标记需要重试的方法.没有工作......我也试过几种方法一样SELECT ... FOR UPDATE,EntityManager.lock(...)

什么是避免陈旧数据,脏读等等的最佳方法?重试?,同步?,JPA锁?,隔离?,选择...进行更新?我无法让它工作,我真的很高兴任何帮助.


这是我想做的一些伪代码:

void doSomething(itemId) {
    select something into A;
    select anotherthing into B;

    // XXX
    item = getItemFormDB( itemId ); // takes long for one user and for other concurrent user it could take less time
    item.setA(A);
    item.setB(B);

    // YYYY
    update item; 
}
Run Code Online (Sandbox Code Playgroud)

在// XXX和// YYY之间,另一个会话可以修改该项,然后抛出StaleObjectStateException.

kna*_*983 10

我得到了一个解决方案,但我觉得它很难看.我捕获所有RuntimeException,它只适用于新事务.你知道怎么做得更好吗?你看到有什么问题吗?

首先,我做了一个注释:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RetryingTransaction {
     int repeatCount() default 20;
}
Run Code Online (Sandbox Code Playgroud)

然后我做了一个像这样的拦截器:

    public class RetryingTransactionInterceptor implements Ordered {
      private static final int DEFAULT_MAX_RETRIES = 20;
      private int maxRetries = DEFAULT_MAX_RETRIES;
      private int order = 1;

      @Resource
      private PlatformTransactionManager transactionManager;

      public void setMaxRetries(int maxRetries) {
          this.maxRetries = maxRetries;
      }
      public int getOrder() {
          return this.order;
      }
      public void setOrder(int order) {
          this.order = order;
      }

      public Object retryOperation(ProceedingJoinPoint pjp) throws Throwable {
          int numAttempts = 0;
          Exception failureException = null;
          do {
                numAttempts++;
                try {
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    TransactionStatus status = transactionManager.getTransaction(def);

                    Object obj = pjp.proceed();

                    transactionManager.commit(status);      

                    return obj;
                } 
                catch( RuntimeException re ) {
                    failureException = re;
                }
          } while( numAttempts <= this.maxRetries );
          throw failureException;
      }
}
Run Code Online (Sandbox Code Playgroud)

Spring applicationConfig.xml:

<tx:annotation-driven transaction-manager="transactionManager" order="10" />

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionSynchronizationName">
        <value>SYNCHRONIZATION_ALWAYS</value>
    </property>
</bean>

<bean id="retryingTransactionInterceptor" class="com.x.y.z.transaction.RetryingTransactionInterceptor">
    <property name="order" value="1" />
</bean>

<aop:config>
    <aop:aspect id="retryingTransactionAspect" ref="retryingTransactionInterceptor">
        <aop:pointcut 
            id="servicesWithRetryingTransactionAnnotation" 
            expression="execution( * com.x.y.z.service..*.*(..) ) and @annotation(com.x.y.z.annotation.RetryingTransaction)"/>
        <aop:around method="retryOperation" pointcut-ref="servicesWithRetryingTransactionAnnotation"/>
    </aop:aspect>
</aop:config>
Run Code Online (Sandbox Code Playgroud)

并且注释方法如下:

@RetryingTransaction
public Entity doSomethingInBackground(params)...
Run Code Online (Sandbox Code Playgroud)


Mar*_*szS 6

当版本号或时间戳检查失败时(发生乐观锁定),使用Spring Retry重试整个方法.

组态

@Configuration
@EnableRetry
public class FooConfig {
     ...
}
Run Code Online (Sandbox Code Playgroud)

用法

@Retryable(StaleStateException.class)
@Transactional
public void doSomethingWithFoo(Long fooId){
    // read your entity again before changes!
    Foo foo = fooRepository.findOne(fooId);

    foo.setStatus(REJECTED)  // <- sample foo modification

} // commit on method end
Run Code Online (Sandbox Code Playgroud)

项目配置

Spring Boot应用程序定义了有效的spring-retry版本,因此只需要这样:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency> 
Run Code Online (Sandbox Code Playgroud)