<?php
namespace app\index\controller;
/**
* 秒杀
* @internal
*/
class Skill //extends Backend
{
protected $redis = '';
public function __construct()
{
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function __destruct()
{
$this->redis->close();
}
/**
* 生成商品库存redis
*/
public function goodsRedis()
{
//商品信息 id商品id stock商品库存
$data = input();
foreach ($data as $k => $v) {
$redis_key = 'goods_id_' . $v['id'];
for ($i = 0; $i < $v['stock']; $i++) {
//插入redis中商品的表抢购时从这读取
$this->redis->lPush($redis_key, 1);
}
}
echo "完成";
die;
}
/**
* 抢购
*/
public function skill()
{
$data = input();
//模拟随机用户id
$uid = rand(10000,99999);
//传商品id
$redis_key = 'goods_id_' . $data['id'];
//查询redis中商品的数量长度
$len = $this->redis->lLen($redis_key);
$str = "";
if(!$len || $len<=0){
$str .= $uid."抢购失败,商品售罄";
}else{
$redis_user_name = "goods_id_".$data['id']."_uid";
//判断已抢购列表中是否已存在该用户,获取列表中所有的数据
$skill_user_list = $this->redis->lrange($redis_user_name, 0, -1);
if(in_array($uid, $skill_user_list)){
$str .= $uid."已经抢购成功";
}else{
//从redis商品表中取出一个
$this->redis->rPop($redis_key);
//插入用户抢购成功的redis表中
$this->redis->lPush($redis_user_name,$uid."_".microtime().rand(10000,99999));
$str .= $uid."抢购成功";
}
}
//存日志信息与流程无关
$file = fopen("/www/wwwlogs/redis_log", "a+"); //创建文件或打开文件
fwrite($file, '抢购信息' . '----' . $str . '-------------------' . '时间:' . date('Y-m-d H:i:s', time()) . "\r\n");
echo '完成';
}
}
关注公众号技术谈论:靳某某的PHP爬坑之旅