mysql乐观锁怎么开 360借条平台是合法的吗( 二 )


mysql如何实现乐观锁乐观锁与悲观锁不同的是,它是一种逻辑上的锁,而不需要数据库提供锁机制来支持
当数据很重要,回滚或重试一次需要很大的开销时,需要保证操作的ACID性质,此时应该采用悲观锁
而当数据对即时的一致性要求不高,重试一次不太影响整体性能时 , 可以采用乐观锁来保证最终一致性 , 同时有利于提高并发性
通常,乐观锁采用版本号/时间戳的形式实现:给数据额外增加一个版本号字段进行控制;更新时,若提交的数据所带的版本号与当前记录的版本号一致,则允许变更执行并更新版本号;若不一致 , 则意味着产生冲突 , 根据业务需求直接丢弃并返回失败,或者尝试合并
在MySQL的实践中,常见的一种使用乐观锁的方法,是在需要使用乐观锁的表中,新增一个version字段
例如:
create table product_amount (
id int not null primary key auto_increment,
product_name varchar(64) not null,
selling_amount int not null,
storing_amount int not null,
version int not null
);
当需要更新销售中的商品数量(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) , 更新时分别只关注自己的版本号,这样就不会因为版本号被其它字段修改而失败,提高了并发性
mysql事务隔离级别 以及 悲观锁-乐观锁以上不是重点,重点是 对事务控制语句不熟悉 。
SAVEPOINT identifier : 在事务中 创建保存点 。一个事务中 允许有多个保存点 。
RELEASE SAVEPOINT identifier : 删除保存点 。当事务中 没有指定的 保存点,执行该语句 会抛异常 。
ROLLBACK TO identifier : 把事务回滚到 保存点 。
Say you have a table T with a column C with one row in it, say it has the value '1'. And consider you have a simple task like following:
That is a simple task that issue two reads from table T, with a delay of 1 minute between them.
If you follow the logic above you can quickly realize that SERIALIZABLE transactions, while they may make life easy for you, are always completely blocking every possible concurrent operation, since they require that nobody can modify, delete nor insert any row. The default transaction isolation level of the .Net System.Transactions scope is serializable, and this usually explains the abysmal performance that results.
在Repeatable Read隔离级别下,一个事务可能会遇到幻读(Phantom Read)的问题 。
幻读是指 , 在一个事务中 , 第一次查询某条记录 , 发现没有 , 但是 , 当试图更新这条不存在的记录时,竟然能成功,并且,再次读取同一条记录 , 它就神奇地出现了 。

推荐阅读