解決思路
設置樂觀鎖標識,watch方法為:監視一個(或多個)key,如果在事務執行之前這個(或這些)key被其他命令所為,那么事務將被打斷
隊列使用 內存消耗比較大
redis的watch
multi
exec
方法實現
<?php header("content-type:text/html;charset=utf-8"); $redis = new redis(); $result = $redis->connect('127.0.0.1', 6379); $gots = $redis->get("gots"); // 已搶數量 $robTotal = 100; // 搶購總數量 if ($gots < $robTotal) { $redis->watch("gots"); // 監聽key $redis->multi(); // 開啟事務 //插入搶購數據 $redis->hSet("userList", "user_id_" . mt_rand(1, 9999), time()); $redis->set("gots", $gots + 1); // 搶購到+1 $robResult = $redis->exec(); // 執行事務 if ($robResult) { echo "搶購成功!<br/>"; echo "剩余數量:" . ($robTotal - ($redis->get("gots"))) . "<br/>"; echo "用戶列表:<pre>"; var_dump($redis->hGetAll("userList")); } else { echo "手氣不好,再搶購!"; exit; } }else { echo "已售罄"; exit; }