redis use watch spike rush to complete the function:
Redis completed using two key functions rush spike, mywatchkey for storing the number of users buy and store mywatchlist buy list.
Its advantages are as follows:
1. First choose to buy fast memory database.
2. Fast concurrent nature no not a problem.
3. Use the pessimistic locking, quickly increasing system resources.
4. stronger than the queue, the queue will instantly bursting your memory database resources.
5. Use optimistic locking, achieve comprehensive needs.
I think the following code is certainly 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 $; // number of panic buying
- if($mywatchkey<$rob_total){
- $redis->watch("mywatchkey");
- $redis->multi();
- // set the delay, convenient test results.
- sleep(5);
- // insert snapped 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 "buy success <br/>!";
- echo "remaining number:" (. $ rob_total- $-mywatchkey. 1). "a";
- echo "User List: <pre>";
- var_dump($mywatchlist);
- }else{
- echo "I'm feeling good, then buy!"; Exit;
- }
- }
- ?>