springboot乐观锁
程序员文章站
2022-06-02 11:13:03
...
包依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.188</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.2.6.RELEASE</version>
<scope>test</scope>
</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次,如果均不成功,则判定失败,抛出异常
上一篇: php面试常问的问题