涉及搶購、秒殺、抽獎、搶票等活動時,爲了不超賣,那麼庫存數量是有限的,可是若是同時下單人數超過了庫存數量,就會致使商品超賣問題。那麼咱們怎麼來解決這個問題呢?php
<?php header("content-type:text/html;charset=utf-8"); $redis = new redis(); $result = $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); if ($rob_result) { $mywatchlist = $redis->hGetAll("mywatchlist"); echo '搶購成功' . PHP_EOL; echo '剩餘數量:' . ($rob_total - $len - 1) . PHP_EOL; echo '用戶列表:' . PHP_EOL; print_r($mywatchlist); exit; } else { exit('手氣很差,再搶購!'); } } else { exit('已賣光'); }