秒杀

来源:互联网 发布:易语言键盘钩子源码 编辑:程序博客网 时间:2024/04/30 12:59
<?php$redisServer = RedisServer::getInstance();$listKey = 'miaoshaK';file_lock('qiang', $redisServer);//读取有效的请求while($res = $redisServer->lpop($listKey)){error_log($res."\n", 3,'log.txt');echo '购买成功去支付';}//文件锁阻挡并发function file_lock($fun, $param){$fp = fopen("lock.txt", "w+"); if(flock($fp, LOCK_EX|LOCK_NB)){call_user_func($fun, $param);flock($fp,LOCK_UN);}else{echo "没有商品了";}fclose($fp);}//有效的前几次请求写入队列  超出库存 返回 没有商品function qiang($redisServer){$listKey = 'miaoshaK';$len = $redisServer->get('miaosha');$len = empty($len) ? 1 : ++$len;if($len >10){echo '没有了';return false;}else{$data= array('uid'=> $len,'url'=> 'http://xxx.com');$redisServer->rPush($listKey, json_encode($data));$redisServer->rPush('testkey', json_encode($data));$redisServer->set('miaosha', $len);}}class RedisServer{private static $_instance = null;public $redis;protected  function __construct(){$this->redis = new Redis();$this->redis->connect('127.0.0.1',6379);$this->redis->auth('123456');return $this->redis;}public static function getInstance(){if(is_null(self::$_instance)){self::$_instance = new self();}return self::$_instance;}public function set($key, $val){$this->redis->set($key, $val);}public function get($key){return $this->redis->get($key);}//从尾部写入public function rPush($key, $data){$this->redis->rpush($key, $data);}//从头部弹出public function lpop($key){return $this->redis->lpop($key);}//public function llen($key){return $this->redis->llen($Key);}}?>

0 0