springboot乐观锁

包依赖

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值