Mybatis-Plus 乐观锁插件

一、场景

        一件商品,成本价是 80 元,售价是 100 元。老板先是通知小李,说你去把商品价格增加 50 元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到 150 元,价格太高,可能会影响销量。又通知小王,你把商品价格降低 30 元。

        此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格 100 元;小王也在操作,取出的商品价格也是 100 元。小李将价格加了 50 元,并将 100+50=150 元存入了数据库;小王将商品减了 30 元,并将 100-30=70 元存入了数据库。是的,如果没有锁,小李的操作就完全被小王的覆盖了。

        现在商品价格是 70 元,比成本价低 10 元。几分钟后,这个商品很快出售了 1千多件商品,老板亏 1万多。

二、乐观锁与悲观锁

        上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出的被修改后的价格,150 元,这样他会将 120 元存入数据库。

        如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也会保证最终的价格是 120 元。

三、模拟修改冲突

3.1 创建库表

CREATE TABLE t_product
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称',
	price INT(11) DEFAULT 0 COMMENT '价格',
	VERSION INT(11) DEFAULT 0 COMMENT '乐观锁版本号',
	PRIMARY KEY (id)
);

INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);

3.2 创建实体

@Data
public class Product {
    private Long id;
    private String name;
    private Integer price;
    private Integer version;
}

3.3 创建 mapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mybatisplus.entity.Product;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductMapper extends BaseMapper<Product> {
    
}

3.4 测试

        可以看到,确实出现了价格覆盖,最终的价格变成了 70 元。

    @Test
    public void testConcurrentUpdate() {
        // 1、小李
        Product p1 = productMapper.selectById(1L);
        System.out.println("小李取出的价格:" + p1.getPrice());
        // 2、小王
        Product p2 = productMapper.selectById(1L);
        System.out.println("小王取出的价格:" + p2.getPrice());

        // 3、小李将价格加了50元,存入了数据库
        p1.setPrice(p1.getPrice() + 50);
        int result1 = productMapper.updateById(p1);
        System.out.println("小李修改结果:" + result1);

        // 4、小王将商品减了30元,存入了数据库
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改结果:" + result2);

        // 最后的结果
        Product p3 = productMapper.selectById(1L);
        // 价格覆盖,最后的结果:70
        System.out.println("最后的结果:" + p3.getPrice());
    }

四、乐观锁实现流程

4.1 实现思想

        在数据库表中添加 version 字段,取出记录时,获取当前 version,当执行更新操作时,version + 1,如果 where 语句中的 version 版本不对,则更新失败。

4.2 Mybatis-Plus 实现乐观锁

        首先,修改实体类 Product,添加 @Version 注解,用于标识出该字段为控制版本的 version 字段,如下:

@Data
public class Product {
    private Long id;
    private String name;
    private Integer price;
    @Version
    private Integer version;
}

        其次,在配置类中添加乐观锁插件配置,如下:

@Configuration
// 可以将主类中的注解移到此处
@MapperScan("com.mybatisplus.mapper")
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 添加乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

4.3 测试

        再次执行测试的代码,输出结果如下所示:

        可以看到,最终小王修改失败了,最终的价格为 150 元,虽然保证了老板不会亏损,但是也没有按照老板的要求,将价格设置成 120 元。

4.4 流程优化

        修改下测试代码,达到老板想要的效果,如下:

    @Test
    public void testConcurrentVersionUpdate() {
        // 小李取数据
        Product p1 = productMapper.selectById(1L);
        // 小王取数据
        Product p2 = productMapper.selectById(1L);
        // 小李修改 + 50
        p1.setPrice(p1.getPrice() + 50);
        int result1 = productMapper.updateById(p1);
        System.out.println("小李修改的结果:" + result1);

        // 小王修改 - 30
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改的结果:" + result2);
        // 判断小王的修改是否成功
        if(result2 == 0){
            // 失败重试,重新获取version并更新
            p2 = productMapper.selectById(1L);
            p2.setPrice(p2.getPrice() - 30);
            result2 = productMapper.updateById(p2);
        }
        System.out.println("小王修改重试的结果:" + result2);
        // 老板看价格
        Product p3 = productMapper.selectById(1L);
        System.out.println("老板看价格:" + p3.getPrice());
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐的小三菊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值