秒杀

<?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);
	}
	

	
}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值