<?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);
}
}
?>
秒杀
最新推荐文章于 2024-08-21 14:38:29 发布