<?php header("content-type:text/html;charset=utf-8"); $t_start_set = microtime(true); $redis = new redis(); $result = $redis->connect('127.0.0.1', 6379); $goods_id=22; $redis->watch("watchGoods_".$goods_id); $len = $redis->hlen("watchGoods_".$goods_id);//已抢购数量 $rob_total = $redis->get('Goods_'.$goods_id.'_totalNum'); // $redis->set('Goods_'.$goods_id.'_totalNum',100) 抢购数量(库存总数)设置100件 if ($len < $rob_total) { $redis->multi(); $redis->hSet("watchGoods_".$goods_id, "user_id_" . mt_rand(1, 999999) .'=====:'.$len, $t_start_set.'->'.microtime(true));//hash表 $rob_result = $redis->exec(); if ($rob_result) { file_put_contents("log.txt", '时间: '.$t_start_set." 进入 success ! 抢到了第:".($len+1).'个商品,库存数量='.($rob_total- $len-1).PHP_EOL, FILE_APPEND); $mywatchlist = $redis->hGetAll("watchGoods_".$goods_id); echo "抢购成功!<br/>"; echo "剩余数量:" . ($rob_total - $len - 1) . "<br/>"; echo "用户列表:<pre>"; var_dump($mywatchlist); } else { file_put_contents("log.txt", '时间: '.$t_start_set.' 进入 ERROR!!手气不好,再抢购 CAS啦 准备抢第'.($len+1).'个,但是CAS机制,别人抢走了。' . PHP_EOL, FILE_APPEND); exit; } } else { file_put_contents("log.txt", '时间: '.$t_start_set.'进入. ^_^ 抢购结束 抢光了 over='.$len . PHP_EOL, FILE_APPEND); $mywatchlist1 = $redis->hGetAll("watchGoods_".$goods_id); echo "用户列表:<pre>"; var_dump($mywatchlist1); }?>
秒杀思路:
1.使用redis 结合watch的乐观锁的特性。CAS[check-and-set OR compare and swap]
参考 http://www.csdn.net/article/2014-11-28/2822858
http://www.cnblogs.com/martinzhang/p/3415204.html
2. CAS
参考 http://blog.csdn.net/chen19870707/article/details/41083183
http://www.cnblogs.com/Mainz/p/3546347.html
http://flychao88.iteye.com/blog/2269438