首页 > 代码库 > Redis案例——商品秒杀,购物车

Redis案例——商品秒杀,购物车

秒杀案例:

 1 <?php   2     header("content-type:text/html;charset=utf-8");   3     $redis = new redis();   4     $result = $redis->connect(‘10.10.10.119‘, 6379);   5     $mywatchkey = $redis->get("mywatchkey");   6     $rob_total = 100;   //抢购数量   7     if($mywatchkey<$rob_total){   8         $redis->watch("mywatchkey");   9         $redis->multi();  10         //设置延迟,方便测试效果。  11         sleep(5);  12         //插入抢购数据  13         $redis->hSet("mywatchlist","user_id_".mt_rand(1, 9999),time());  14         $redis->set("mywatchkey",$mywatchkey+1);  15         $rob_result = $redis->exec();  16         if($rob_result){  17             $mywatchlist = $redis->hGetAll("mywatchlist");  18             echo "抢购成功!<br/>";  19             echo "剩余数量:".($rob_total-$mywatchkey-1)."<br/>";  20             echo "用户列表:<pre>";  21             var_dump($mywatchlist);  22         }else{  23             echo "手气不好,再抢购!";exit;  24         }  25     }  

 

Redis案例——商品秒杀,购物车