springboot乐观锁

来源:互联网 发布:ae cc 2017 mac 中文 编辑:程序博客网 时间:2024/05/17 06:46

包依赖

 <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)@Documentedpublic @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@Componentpublic 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次,如果均不成功,则判定失败,抛出异常

原创粉丝点击