springboot乐观锁

包依赖

 <dependency>
             <groupId>org.springframework.bootgroupId>
             <artifactId>spring-boot-starter-data-jpaartifactId>
             <version>1.2.6.RELEASEversion>
         dependency>

         <dependency>
             <groupId>com.h2databasegroupId>
             <artifactId>h2artifactId>
             <version>1.4.188version>
             <scope>runtimescope>
         dependency>

         <dependency>
             <groupId>org.springframework.bootgroupId>
             <artifactId>spring-boot-starter-testartifactId>
             <version>1.2.6.RELEASEversion>
             <scope>testscope>
         dependency>

加乐观锁
我用的是JPA, 所以很简单,在实体类加一个字段,并注解@Version即可。

通过AOP实现对RetryOnOptimisticLockingFailureException的恢复
1.添加“`

@Target(value = {ElementType.PARAMETER,         ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RetryOnOptimisticLockingFailure {
    String description() default "";
}

再加一个切面

package com.nroad.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017/5/25.
 */
@Aspect
@Component
public class RetryOnOptimisticLockingAspect {
    @Pointcut("@annotation(com.nroad.annotations.RetryOnOptimisticLockingFailure)")
    public void retryOnOptFailure() {}

    public static final int maxRetries = 5;

    @Around("retryOnOptFailure()")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        int numAttempts = 0;
        do {
            numAttempts++;
            try {
                return pjp.proceed();
            } catch (OptimisticLockingFailureException ex) {
                if (numAttempts > maxRetries){
                    throw ex;
                }
            }
        }while (numAttempts < this.maxRetries);
        return null;
    }
}

循环5次,如果均不成功,则判定失败,抛出异常

你可能感兴趣的:(springboot)