之前写了一些辅助工作相关的Spring Boot怎么使用AOP。这里继续正题,怎么减少Spring Boot 乐观锁加锁报错的情况(基本可以解决)。

1. 包依赖

  • spring-boot-starter-data-jpa, Spring Boot的JPA starter
  • h2, H2内存数据库
  • spring-boot-starter-test,Spring Boot的Junit测试starter
         <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>

2. 如何在启用乐观锁?

我用的是JPA, 所以很简单,在实体类加一个字段,并注解@Version。

 @Entity
public class Account { //primary key, auto generated
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id; private String name; // enable optimistic locking version control
@Version
private int version; /*omitted getter/setter, but required*/
}

3. 通过AOP实现对RetryOnOptimisticLockingFailureException的恢复

为了减少对代码的侵入,对之前的AOP例子进行少许修改:

  • 自定义一个注解,用来标注需要恢复这个错误的接口
 @Retention(RetentionPolicy.RUNTIME)
public @interface RetryOnOptimisticLockingFailure { }
  • 切入点表达式使用注解,不再使用execution
     @Pointcut("@annotation(RetryOnOptimisticLockingFailure)")
public void retryOnOptFailure() {
// pointcut mark
}
  
@Around("retryOnOptFailure()")
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
int numAttempts = 0;
do {
numAttempts++;
try {
return pjp.proceed();
} catch (OptimisticLockingFailureException ex) {
if (numAttempts > maxRetries) {
//log failure information, and throw exception
throw ex;
}else{
//log failure information for audit/reference
//will try recovery
}
}
} while (numAttempts <= this.maxRetries); return null;
}
  • 在需要对错误进行恢复的RESTFul接口加上恢复标签

至于为什么一定是要在RESTFul接口上加,而不是其他地方(例如service层),是因为Spring Boot的事务管理的上下文是从resource层开始建立的,在service层恢复是无效的,因为数据库的操作依然是在之前失败的事务里,之后再细说吧。

 @RestController
@RequestMapping("/account")
public class AccountResource { @Autowired
private AccountService accountService; @RequestMapping(value = "/{id}/{name}", method = RequestMethod.PUT)
@ResponseBody
@RetryOnOptimisticLockingFailure
public void updateName(@PathVariable Integer id, @PathVariable String name) {
accountService.updateName(id, name);
}
}

4. 测试用例

@Test
public void testUpdate() {
new Thread(() -> this.client.put(base + "/1/llt-2", null)).start();
new Thread(() -> this.client.put(base + "/1/llt-3", null)).start(); try {
//waiting for execution result of service
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

5. 测试一下效果如何

  • 没有在AccountResource的updateName方法加@RetryOnOptimisticLockingFailure:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.ObjectOptimisticLockingFailureException: Object of class [com.leolztang.sb.aop.model.Account] with identifier [1]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.leolztang.sb.aop.model.Account#1]] with root cause

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.leolztang.sb.aop.model.Account#1]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:2541)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3285)
  • 在AccountResource的updateName方法加@RetryOnOptimisticLockingFailure:
Original:name=[llz-1],version=[0],New:name=[llt-2],version=[1]
Original:name=[llt-2],version=[1],New:name=[llt-3],version=[2]

6. 完整代码

http://files.cnblogs.com/files/leolztang/sb.aop-v2.tar.gz

Spring Boot 乐观锁加锁失败 - 使用AOP恢复错误的更多相关文章

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

    Spring Boot with AOP 手头上的项目使用了Spring Boot, 在高并发的情况下,经常出现乐观锁加锁失败的情况(OptimisticLockingFailureException ...

  2. spring boot 中@Autowired注解无法自动注入的错误

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/huihuilovei/article/de ...

  3. spring boot 分布式锁组件 spring-boot-klock-starter

    基于redis的分布式锁spring-boot starter组件,使得项目拥有分布式锁能力变得异常简单,支持spring boot,和spirng mvc等spring相关项目 快速开始 sprin ...

  4. 2020最新的Spring Boot 分布式锁的具体实现(内附代码)

    前言 面试总是会被问到有没有用过分布式锁.redis 锁,大部分读者平时很少接触到,所以只能很无奈的回答 "没有".本文通过 Spring Boot 整合 redisson 来实现 ...

  5. 如何优雅地在 Spring Boot 中使用自定义注解,AOP 切面统一打印出入参日志 | 修订版

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...

  6. spring boot 从开发到上线(三)—AOP 异常监控、上报

    在做这个项目的期间,看到一篇很有启发性的文章<程序员你为什么这么累>.对于初级程序员来说,拿到需求,第一反应是用什么技术来尽快的完成任务,这本身并没有问题.但长此以往,不仅被需求的更改搞得 ...

  7. spring boot开发 @autowired注入失败

    @autowired注入失败 会出现如下错误提示: 2018-05-28 08:39:41.857 INFO 8080 --- [ restartedMain] org.hibernate.Versi ...

  8. spring boot下接口调用失败重试方案

    背景: 在项目开发中,有时候会出现接口调用失败,本身调用又是异步的,如果是因为一些网络问题请求超时,总想可以重试几次把任务处理掉. 一些RPC框架,比如dubbo都是有重试机制的,但是并不是每一个项目 ...

  9. Spring Boot 中使用自定义注解,AOP 切面打印出入参日志及Dubbo链路追踪透传traceId

    一.使用背景 开发排查系统问题用得最多的手段就是查看系统日志,在分布式环境中一般使用 ELK 来统一收集日志,但是在并发大时使用日志定位问题还是比较麻烦,由于大量的其他用户/其他线程的日志也一起输出穿 ...

随机推荐

  1. LAMP环境配置 linux+apache+mysql+php

    虚拟机安装Linux系统: 新建虚拟机过程中选择Linux,下面选择centos或者是Ubuntu Linux切换图像命令:注意只有装了图像界面才可以切换 查看安装环境的版本: rpm -qa 查看安 ...

  2. BZOJ1298[SCOI2009]骰子的学问

    Description Input 第一行为两个整数n, m.第二行有n个整数,为a1,a2, -, an. Output 包含n行,每行m个1~n×m的正整数,各不相同,以空格分开.如果有多解,输出 ...

  3. [LeetCode] Matchsticks to Square 火柴棍组成正方形

    Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match ...

  4. 20145215&20145307《信息安全系统设计基础》实验二 固件设计

    20145215&20145307<信息安全系统设计基础>实验二 固件设计 实验目的与要求 了解多线程程序设计的基本原理,学习 pthread 库函数的使用. 了解在 linux ...

  5. 基于C/S架构的3D对战网络游戏C++框架 _【不定期更新通知】

    由于笔者最近有比赛项目要赶,这个基于C/S架构的3D对战网络游戏C++框架也遇到了一点瓶颈需要点时间沉淀,所以近一段时间不能保证每天更新了,会保持不定期更新.同时近期笔者也会多分享一些已经做过学过的C ...

  6. [EF2]Sneak Preview: Persistence Ignorance and POCO in Entity Framework 4.0

    http://blogs.msdn.com/b/adonet/archive/2009/05/11/sneak-preview-persistence-ignorance-and-poco-in-en ...

  7. ServerSocket的介绍

    导语 仅仅只有Socket类是不足以编写服务器的.要创建一个Socket,你需要知道希望连接哪个Internet主机.编写服务器程序时,无法预先了解哪个主机会联系你,即使确实知道,你也不清楚那个主机希 ...

  8. SQL基础语法(五)

    SQL INSERT INTO 语句INSERT INTO 语句 INSERT INTO 语句用于向表格中插入新的行. 语法:INSERT INTO 表名称 VALUES (值1, 值2,....) ...

  9. MVC项目中,如何访问Views目录下的静态文件!

    <!--注意,是system.webServer节点,而非system.web--><system.webServer> <handlers> <add na ...

  10. Jmeter学习笔记TWO

    使用非GUI模式运行Jmeter脚本并自动生成测试报告 命令:jmeter -n -t tougu.jmx -l result.jtl -e -o /tmp/ResultReport 这个命令是用于执 ...