connect('127.0.0.1',6379);$mywatchkey=$redis- >get("");$rob_total=10;//Snap-up quantity if($mywatchkeywatch("mywatchkey");$redis->multi();//Set the delay to facilitate testing the effect. sleep(5);// Insert rush purchase data $redi"/> connect('127.0.0.1',6379);$mywatchkey=$redis- >get("");$rob_total=10;//Snap-up quantity if($mywatchkeywatch("mywatchkey");$redis->multi();//Set the delay to facilitate testing the effect. sleep(5);// Insert rush purchase data $redi">
header(“content-type:text/html;charset=utf-8”);
$redis = new redis();
$result = $redis->connect('127.0.0.1 ', 6379);
$mywatchkey = $redis->get("");
$rob_total = 10;
//Snap-up quantity
if($mywatchkey<$rob_total) {
$redis->watch("mywatchkey");
$redis->multi();
//Set the delay to facilitate testing the effect.
sleep(5);
//Insert rush purchase data
$redis->hSet("mywatchlist","user_id_".mt_rand(1, 9999),time());
$ redis->set("mywatchkey",$mywatchkey 1);
$rob_result = $redis->exec();
if($rob_result) {
$mywatchlist = $redis-> hGetAll("mywatchlist");
echo "Purchase successful!";
echo "Remaining quantity:".($rob_total-$mywatchkey-1)."";
echo "User list:";
var_dump($mywatchlist);
} else {
echo “If you’re not lucky, buy again!”;
exit;
}
}
The above is the detailed content of How to use php+redis to implement optimistic locking. For more information, please follow other related articles on the PHP Chinese website!