前言🍭
❤️❤️❤️SSM专栏更新中,各位大佬觉得写得不错,支持一下,感谢了!❤️❤️❤️
上篇讲了增删的操作,这篇讲修改操作中的一个问题以及它对应的解决方案——乐观锁,还有代码生成器的实现。
一、乐观锁(update)🍭
业务并发现象带来的问题: 秒杀。
我们应该都遇过买东西限量秒杀吧,这个时候这么多人一起抢,我们应该怎么去实现秒杀程序呢?
下面我们会讲解2000访问量的秒杀实现,如果是更多人的话就应该使用其他更好的方法了。
1、添加字段和实体类属性🍉
添加version字段,默认值为1
实体类属性也添加应该version属性:
package com.example.domain;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@Data
/*@TableName("tbl_user")*/
public class User {
@TableId(type= IdType.ASSIGN_ID)
private Long id;
private String name;
@TableField(value = "pwd",select = false)
private String password;
private Integer age;
private String tel;
/*@TableLogic(value = "0",delval = "1")*/
private Integer deleted;
@Version
private Integer version;
@TableField(exist = false)
private Integer online;
}
2、@Version原理🍉
当人人去进行秒杀时,成功抢到商品的用户,会更新用户的version值,
update set_abc=1,version = version + 1 where version=1
如上面这个SQL一样。当一个仅剩的一个商品被抢走,这个version值就会变化,其他人就会显示抢不到商品。
添加乐观锁拦截器(和分页功能一样)🍓
使用这个和分页功能一样,需要添加拦截器:
package com.example.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
@Bean
public MybatisPlusInterceptor mpInterceptor(){
//1.定义Mp拦截器
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
//2.添加具体的拦截器
mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
//3、添加乐观锁拦截器
mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mpInterceptor;
}
}
3、测试代码🍓
我们去修改用户id=2的用户名:
@Test
void testUpdate(){
User user=new User();
user.setId(2L);
user.setName("编程");
userDao.updateById(user);
}
运行发现,version值并没有发生改变: