MySQL乐观锁

乐观锁(版本控制/条件过滤)

使用 MySQL 5.7 做测试,数据库引擎为 InnoDB,

数据库隔离级别为可重复读(REPEATABLE-READ),

image-20240827102432439

读读共享,读写互斥。[深刻理解这句:两个不同事物可以同时读取一条记录,但是不能同时写一条事物(也就是写是互斥的)]

在这个隔离级别下,在多事务并发的情况下,还是会出现数据更新的冲突问题。

乐观锁的实现:

使用版本控制字段,再利用行锁的特性实现乐观锁,如下

有一张订单表order,有字段id、order_no、 price, 为实现乐观锁控制,添加version字段,默认值为0

id 1
order_no 123456
price 5
version 0

假设两个人同时进来修改该条数据,操作为:

1. 先查询该数据 select * from order where id = 1

2. 修改该条数据 update order set price = 1 where id = 1

如果两个人同时查询到该条数据price = 5, 可以执行update操作, 但任意一方还没执行update操作,那么最后双方都执行update,导致数据被修改两次,产生脏数据 !

使用version字段控制版本后:

1. 两人先查询该数据 select * from order where id = 1

此时两人查询到的数据一样,id = 1, price = 5, order_no = 123456, version = 0

  1. 两人都发现该条数据price = 5, 符合update条件,第一人执行update(因为mysql行锁的特性,两人不可能同时修改一条数据,所以update同一条数据的时候,是有先后顺序的,只有在第一个执行完update,才能释放行锁,第二个继续进行update):

update order set price = 1, version = version + 1 where id = 1 and version = 0

执行完成后,version字段值将变成1, 第二人执行update:

update order set price = 1, version = version + 1 where id = 1 and version = 0

此时的version的值已经被修改为1,所以第二人修改失败,实现乐观锁控制。

死锁的处理:

数据库使用乐观锁导致产生死锁:

事务A

update order set price = 1 where id = 1

update order set price = 2 where id = 2

事务B

update order set price = 1 where id = 2

update order set price = 2 where id = 1

假设在两个事务中有以上两个操作,同时修改order表中两条数据

事务A在执行完第一条update的时候,刚好事务B也执行完第一条update

此时, 事务A中order表中的id = 1的行被锁住, 事务B中order表中id = 2的行被锁住,两个事务继续往下执行

事务A中第二条update执行需要order表中id = 2的行数据,而事务B中第二条update执行需要id = 1的行数据, 两条update往下执行的条件都需要对方事务中已经被锁住的行,于是陷入无限等待,形成死锁。

解决死锁的产生:

指定锁的执行顺序,比如把以上两事务稍作修改

事务A

update order set price = 2 where id = 2

update order set price = 1 where id = 1

事务B

update order set price = 1 where id = 2

update order set price = 2 where id = 1

事务A执行第一条update时,id = 2 的行被锁住,此时,事务B想修改id = 2的行,只能等待事务A执行完成,当事务A执行完成时,事务B再执行, 这样就不会产生死锁了。

场景再现:

销量表 goods_sale ,表结构如下:

字段 数据类型 说明
goods_sale_id varchar(32) 销量 id
goods_id varchar(32) 商品 id
count int(11) 销量

比如在某一时刻事务 A 和事务 B,在同时操作表 goods_sale 的 goods_id = 20191017344713049535651840506935 的数据,当前销量为 100。

goods_sale_id goods_id count
20191017344778600995856384326638 20191017344713049535651840506935 100

两个事务的内容一样,都是先读取的数据,count +100 后更新。

我们这里只讨论乐观锁的实现,为了便于描述,假设项目已经集成 Spring 框架,使用 MyBatis 做 ORM,Service 类的所有方法都使用了事务,事务传播级别使用 PROPAGATION_REQUIRED ,在事务失败会自动回滚。

Service 为 GoodsSaleService ,更新数量的方法为 addCount()

@Service
@Transaction
pubic class GoodsSaleService  {
    
    @Autowire
    private GoodsSaleDao dao;
    
    public void addCount(String goodsId, Integer count) {
        GoodsSale goodsSale = dao.selectByGoodsId(goodsId);
        if (goodsSale == null) {
            throw new Execption("数据不存在");
        }
        int count = goodsSale.getCount() + count;
        goodsSale.setCount(count);
        int count = dao.updateCount(goodsSale);
        if (count == 0) {
            throw new Exception("添加数量失败");
        }
    }
    
}

使用的 Dao 为 GoodsSaleDao ,有两个方法

public interface GoodsSaleDao {
    
    GoodsSale selectByGoodsId(@Param("goodsId") String goodsId);
    
    int updateCount(@Param("record") GoodsSale goodsSale);
}

mapper 文件对应的 sql 操作为:

<!-- 查询 -->
<select id="selectByGoodsId" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from goods_sale
    where goods_id = #{goodsId}
</select>
 
<!-- 更新 -->
<update id="updateCount">
    update
    goods_sale
    set count = #{record.count},
    where goods_sale_id = #{record.goodsSaleId}
</update>

好了,假设现在有两个线程同时调用了 GoodsSaleService#addCount ,操作同一行数据,会有什么问题?

假设这两个线程对应的事务分为事务 A 和事务 B。用一张流程图来说明问题:

img

MySQL-多事务更新冲突

更新冲突了!两次 addCount(100) ,结果应该是 300,结果还是 200。

该如何处理这个问题,有一个简单粗暴的方法,既然这里多线程访问会有线程安全问题,那就上锁,方法加入 synchronized 进行互斥。

实现方式1:程序实现-----加锁用synchronlized

public synchronized void addCount(String goodsId, Integer count) {
    ...
}

这个方案确实也可以解决问题,但是这种简单互斥的做法,锁的粒度太高,事务排队执行,并发度低,性能低。但如果是分布式应用,还得考虑应用分布式锁,性能就更低了。

实现方式2:数据库实现

乐观锁方式1:版本控制+自旋

考虑到这些更新冲突发生的概率其实并不高。这里讨论另一种解决方案,使用数据库乐观锁来实现。

原理就是基于 CAS ,比较并交换数据,如果发现被更新过了,直接更新失败。

然后加入自旋(自循环)接着更新,直到成功。乐观就在于我们相信冲突发生概率低,

如果发生了,就用一种廉价的机制迅速发现,快速失败。

我们来讨论如何实现它。数据库表 GoodsSale 新增一行 data_version 来记录数据更新的版本号。新的表结构如下:

字段 数据类型 说明
goods_sale_id varchar(32) 销量 id
goods_id varchar(32) 商品 id
count int(11) 销量
data_version int(11) 版本号

GoodsSaleDao#updateCount 对应的 mapper 的 SQL 语句进行调整,数据更新的时候同时进行 data_version = data_version + 1 ,执行这个 sql 时候已经对数据上行锁了,所以这个 data_version 加 1 的操作为原子操作。

<!-- 乐观锁更新 -->
<update id="updateCount">
    update
    goods_sale
    set count = #{record.count}, data_version = data_version + 1
    where goods_sale_id = #{record.goodsSaleId}
    and data_version = #{record.dataVersion}
</update>
posted @   蜡笔小新Belief  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示