遇到抢购、秒杀、抽奖、抢票等活动时,为避免超卖,库存数量有限,但如果下单人数过多同时超出库存数量,会导致商品超卖。那么我们如何解决这个问题呢?采用乐观锁,使用redis实现connect('127.0.0.1',7379);$redis->watch("mywatchlist");$len=$redis->hlen("mywatchlist");$rob_total=100;//购买次数if($len<$rob_total){$redis->multi();$redis->hSet("mywatchlist","user_id_".mt_rand(1,999999),time());$rob_result=$redis->exec();file_put_contents("log.txt",$len.PHP_EOL,FILE_APPEND);如果($rob_result){$mywatchlist=$redis->hGetAll("mywatchlist");echo'购买成功'.PHP_EOL;echo'剩余数量:'.($rob_total-$len-1).PHP_EOL;echo'用户列表:'.PHP_EOL;print_r($mywatchlist);出口;}else{exit('倒霉,再买!');}}else{exit('售罄');}
