Home > Article > Backend Development > Redis uses watch to complete the flash sale function code
This article mainly introduces the code about Redis using watch to complete the flash sale function. It has a certain reference value. Now I share it with you. Friends in need can refer to it
redis uses watch Complete the flash sale function:
Use two keys in redis to complete the flash sale function. Mywatchkey is used to store the rush purchase quantity and mywatchlist user stores the rush purchase list.
Its advantages are as follows:
1. First, use an in-memory database to achieve extremely fast buying speed.
2. Fast speed and concurrency are not a problem.
3. Using pessimistic locking will quickly increase system resources.
4. Much better than queues, queues will instantly overflow your memory database resources.
5. Use optimistic locking to meet comprehensive needs.
I think the following code is definitely what you want.
<?php header("content-type:text/html;charset=utf-8"); $redis = new redis(); $result = $redis->connect('10.10.10.119', 6379); $mywatchkey = $redis->get("mywatchkey"); $rob_total = 100; //抢购数量 if($mywatchkey<$rob_total){ $redis->watch("mywatchkey"); $redis->multi(); //设置延迟,方便测试效果。 sleep(5); //插入抢购数据 $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 "抢购成功!<br/>"; echo "剩余数量:".($rob_total-$mywatchkey-1)."<br/>"; echo "用户列表:<pre class="brush:php;toolbar:false">"; var_dump($mywatchlist); }else{ echo "手气不好,再抢购!";exit; } } ?>
Related recommendations:
Detailed explanation of how to use python redis
The above is the detailed content of Redis uses watch to complete the flash sale function code. For more information, please follow other related articles on the PHP Chinese website!