我们在面试过程中都会被问到乐观锁,这个东西,其实这个东西并不麻烦,很简单
乐观锁:顾名思义是十分乐观的,他总是认为不会出现问题的,无论干什么都不会上锁!!如果出现问题,就会再次更新新值测试。
悲观锁:顾名思义是十分悲观的,他总是认为会出现问题,无论干什么都会上锁,在操作。
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
--A线程
> update user set name='zhangshan',version=version+1 where id=1 and version=1
--B线程抢先A完成修改操作,这个时候version=1,就会导致A线程修改失败
> update user set name='zhangshan',version=version+1 where id=1 and version=1
1、在数据库表中新增字段version
2、在实体类中同步字段,并添加相应的注解
@Version //乐观锁version注解
private int version;
3、注册组件
@MapperScan("com.example.demo.dao") //扫描mapper文件夹
@EnableTransactionManagement //自动管理事务
@Configuration //配置类
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor OptimisticLockerInnerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
4、到目前为止,乐观锁配置完成了,接下来就是测试乐观锁
1、测试单线程的乐观锁
@RequestMapping("/version")
public void version(){
Student student=studentService.selectById(5);
student.setName("网二");
studentService.updateById(student);
}
从图中可以看得到我们获取了乐观锁之后进行修改成功,version自动加一
2、测试多线程的乐观锁
@RequestMapping("/version2")
public void version2(){
Student student=studentService.selectById(5);
student.setName("线程一");
Student student1=studentService.selectById(5);
student1.setName("线程二");
studentService.updateById(student1);
studentService.updateById(student);
}
在图中可以看到线程一被线程二抢先修改完成后,version+1,导致线程一获取不到原来的version,修改失败。