mysql实现乐观锁

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

 

当需要更新销售中的商品数量(selling_amount)时,使用如下的SQL语句:

update product_amount set selling_amount = #{selling_amount}, version = #{new_version} where id=#{id} and version = #{old_version};

若该语句返回1,则表示更新成功;若返回0,则表示前后的version不一致,产生冲突,更新失败

对于更新仓库中的商品数据(storing_amount)时,也是同理

不过,这样为每行记录都统一设置一个version字段的乐观锁方式,存在一个问题:上例中,如果同时需要单独对selling_amount及storing_amount进行update(两条SQL语句分别单独执行),那么后执行的一条会因为先执行的一条更新了version字段而失败,而这种失败显然是没有必要的,白白浪费了开销

一种比较好的方式是为每个需要乐观锁的字段单独设置版本号,例如对上例的改造:

create table product_amount (

id int not null primary key auto_increment,

product_name varchar(64) not null,

selling_amount int not null,

selling_version int not null,

storing_amount int not null,

storing_version int not null

);

selling_amount和storing_amount分别拥有自己的乐观锁版本号(selling_version和storing_version),更新时分别只关注自己的版本号,这样就不会因为版本号被其它字段修改而失败,提高了并发性
 ———————————————— 
版权声明:本文为CSDN博主「有点发红」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sadfishsc/article/details/51027958

你可能感兴趣的:(工作日志)