baseRedis.php
<?php
/**
* 商品秒杀
* Class YangRedis
*/
class YangRedis
{
// object redis资源
protected $redis;
// string key统一初始前缀
protected $prefix = "goods_";
/**
* 初始化,链接redis
*/
public function __construct()
{
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);//初始化Redis服务器
$this->redis->auth('123456');//密码验证,需要就加
}
/**
* 为每个商品赋值一个队列,库存数量就是队列长度
* 如果这个商品的队列已存在,则在该队列头部继续添加
* @param int $goods_id 商品id
* @param int $num 商品库存
* @param bool $del 是否删除已有的队列,默认删除
* return int 返回队列长度
*/
public function add($goods_id, $num, $del = true)
{
$key = $this->prefix . $goods_id;
//删除已有队列
if ($del) {
$this->delKey($goods_id);
}
//设置秒杀的商品队列,从队列的头部循环添加添加元素
for ($i = 1; $i <= $num; $i++) {
$this->redis->lpush($key, $i);
}
//返回当前商品的队列长度
return $this->redis->llen($key);
}
/**
* 删除key
* @param int $goods_id 商品id
* return int 返回删除成功数量
*/
public function delKey($goods_id)
{
$key = $this->prefix . $goods_id;
return $this->redis->del($key);
}
/**
* 设置key的有效时间,从当前时间往后的n秒后过期
* @param int $goods_id 商品id
* @param int $time 过期时间(单位:秒)
* return bool true|false
*/
public function setEndTime($goods_id, $time)
{
$key = $this->prefix . $goods_id;
return $this->redis->expire($key, $time);
}
/**
* 向队列中写入一个值,用于回仓,回仓前判断该商品的秒杀时间是否到期。(订单未支付取消时使用)
* @param int $goods_id 商品id
* @param int $num 商品库存
* return int 返回增加库存后商品的队列长度
*/
public function setList($goods_id, $num = 1)
{
$key = $this->prefix . $goods_id;
//增加秒杀的商品队列,从队列的头部循环添加添加元素
for ($i = 1; $i <= $num; $i++) {
$this->redis->lpush($key, $i);
}
return $this->redis->llen($key);
}
/**
* 获取队列中所有值
* @param int $goods_id 商品id
* return bool
*/
public function getAllList($goods_id)
{
$key = $this->prefix . $goods_id;
return $this->redis->lRange($key, 0, $this->redis->llen($key) - 1);
}
/**
* 从队列中取值(用户秒杀抢购使用,如果不是false,表示秒杀成功)
* @param int $goods_id 商品id
* return string/bool 如果队列中还有值,则将队列尾部的值取出返回,如果队列为空,则返回false
*/
public function getOut($goods_id)
{
$key = $this->prefix . $goods_id;
return $this->redis->rPop($key);//从队列的尾部取值,先入先出
}
}
执行文件
<?php
include "baseRedis.php";
echo '<pre>';
$re= new YangRedis();
$res= $re->add(10001,5);var_dump($res);//添加
//$res = $re->setEndTime(10001,10);var_dump($res);//设置key的有效时间
//$res = $re->setList(10001);var_dump($res);//从队列的头部值,先入先出
if($res){
echo '初始化库存成功';
}else{
echo '初始化库存失败';
}
<?php
include "baseRedis.php";
echo '<pre>';
$re= new YangRedis();
$res= $re->getOut(10001);var_dump($res);//从队列的尾部取值,先入先出
if($res){
echo '抢购成功';
}else{
echo '抢购失败';
}