Spring Boot 乐观锁加锁失败

Spring Boot with AOP

手头上的项目使用了Spring Boot, 在高并发的情况下,经常出现乐观锁加锁失败的情况(OptimisticLockingFailureException,同一时间有多个线程在更新同一条数据)。为了减少直接向服务使用者直接返回失败结果的情况,可以使用这种方式解决这个问题:

  • 捕获到OptimisticLockingFailureException之后,尝试一定次数的重试。超过重试次数再报错
  • 为了不修改原有的业务方法的代码,使用AOP来实现错误处理功能

先通过一个RESTFul应用看看Spring Boot怎么用AOP,之后再来处理乐观锁加锁失败的问题。关于怎么用Spring Boot创建RESTFul应用不在这里细说了。

1.Maven依赖包

 1     <dependencies>
 2         <dependency>
 3             <groupId>org.springframework.boot</groupId>
 4             <artifactId>spring-boot-starter-web</artifactId>
 5             <version>1.2.6.RELEASE</version>
 6         </dependency>
 7         <!-- AOP的依赖包-->
 8         <dependency>
 9             <groupId>org.springframework.boot</groupId>
10             <artifactId>spring-boot-starter-aop</artifactId>
11             <version>1.2.6.RELEASE</version>
12         </dependency>
13 
14         <dependency>
15             <groupId>junit</groupId>
16             <artifactId>junit</artifactId>
17             <scope>test</scope>
18             <version>4.12</version>
19         </dependency>
20     </dependencies>

2.创建切面定义类

请注意这里用到的几个标签都是必须的,否则没效果。
 1 @Aspect
 2 @Configuration
 3 public class HelloAspect {
 4 
 5     //切入点在实现类的方法,如果在接口,则会执行doBefore两次
 6     @Pointcut("execution(* com.leolztang.sb.aop.service.impl.*.sayHi(..))")
 7     public void pointcut1() {
 8     }
 9 
10     @Around("pointcut1()")
11     public Object doBefore(ProceedingJoinPoint pjp) throws Throwable {
12         System.out.println("doBefore");
13         return pjp.proceed();
14     }
15 }

3.在应用程序配置文件application.yml中启用AOP

spring.aop.auto: true

完成之后启动App,使用RESTFul客户端请求http://localhost:8080/greeting/{name}就可以看到控制台有输出"doBefore",说明AOP已经生效了。

 源代码地址:http://files.cnblogs.com/files/leolztang/sb.aop.tar.gz

 第二部分在这里:http://www.cnblogs.com/leolztang/p/5450316.html

原文地址:https://www.cnblogs.com/leolztang/p/5448480.html