update Item set count=count+1 where id=$id and count=$count; 大致逻辑: try=0; while true do select * from item where id=1; if $count >=40 then close item; break end if ++try >10 then break end update item count=count+1 where id=$id and count=$count; if update ok then xxxx break; end end
这种应用场景可以考虑memcache或redis。 mysql高并发下就得使用锁机制了。 InnoDB引擎,该引擎支持行锁,支持事务,外键。 可以使用 for update 来共享锁,结合事务如下。 begin; select price from good where id=1for update;//查询当前商品的价格 for update 一定要加上 然后判断是否达到40 没有达到40执行
update good set price=price+1 where id=1 最后(再提交之前 你再开一个mysql客户端 来操作这条数据 你会发现一直在等待锁解除) commit
update Item set count=count+1 where id=$id and count=$count;
大致逻辑:
try=0;
while true do
select * from item where id=1;
if $count >=40 then close item; break end
if ++try >10 then break end
update item count=count+1 where id=$id and count=$count;
if update ok then
xxxx
break;
end
end
这种应用场景可以考虑memcache或redis。
mysql高并发下就得使用锁机制了。
InnoDB引擎,该引擎支持行锁,支持事务,外键。
可以使用 for update 来共享锁,结合事务如下。
begin;
select price from good where id=1for update;//查询当前商品的价格 for update 一定要加上
然后判断是否达到40
没有达到40执行
达到的话就回滚终止
锁是计算机协调多个进程或线程并发访问某一资源的机制,为了保证数据的一致性和有效性。
锁分为表锁、行锁还有页面锁,高并发的环境我推荐用行锁。
表级锁
开销小,加锁快;不会出现死锁;锁定粒度大,发生锁冲突的概率最高,并发度最低;适合查询操作较多
行级锁
开销大,加锁慢;会出现死锁;锁定粒度最小,发生锁冲突的概率最低,并发度也最高。适合并发更新数据
页面锁
开销和加锁时间介于表锁和行锁之间;会出现死锁;锁定粒度介于表锁和行锁之间,并发度一般。