Spring Boot 乐观锁加锁失败 - 集成AOP

时间:2025-03-17 23:34:43

Spring Boot with AOP

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

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

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

1.Maven依赖包

     <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
<!-- AOP的依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>1.2.6.RELEASE</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>4.12</version>
</dependency>
</dependencies>

2.创建切面定义类

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

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