```
<?php
namespace app\home\controller;
use think\Controller;
use app\home\model\Rush;//记录抢购成功表
use app\home\model\RushLog;//记录重复抢购用户信息
class Goods extends Controller{
//当前用户ID
protected $user_id;
//商品库存队列
protected $goods_store;
//记录用户抢购成功的队列
protected $goods_rob_success;
//参与抢购的用户队列
protected $user_store;
/**
* 初始化
*/
protected function initialize()
{
//当前商品ID
$goods_id = 30;
//当前用户ID(这里为了测试,所以随机获取)
$this->user_id = rand(10000, 10050);
//商品库存队列
$this->goods_store = 'goods_store_'.$goods_id;
//记录用户抢购成功的队列
$this->goods_rob_success = 'goods_rob_success_'.$goods_id;
//参与抢购的用户队列
$this->user_store = 'user_store_'.$goods_id;
}
/**
* 初始化Redis连接
* @access private
* @return resource
*/
private function connectRedis()
{
//配置
$redis_config = config('redis.');
//初始化
$redis = new \Redis();
//链接服务器
$redis->connect($redis_config['REDIS_HOST'],$redis_config['REDIS_PORT']);
//AUTH认证密码
if($redis_config['REDIS_AUTH']){
$redis->auth($redis_config['REDIS_AUTH']);
}
//检测是否连接成功
if( $redis->ping() != '+PONG' ){
exit( "Server is running: " . $redis->ping() );
}
return $redis;
}
//设置商品库存队列
function stock_queue()
{
//初始化连接
$redis = $this->connectRedis();
//商品库存量
$store = 50;
$res = $redis->llen( $this->goods_store );
$count = $store - $res;
for( $i=0; $i<$count; $i++ ){
$redis->lpush( $this->goods_store , 1 );
}
echo $redis->llen( $this->goods_store );
}
//抢购处理
function index()
{
//用户信息
$userinfo = [
'user_id' => $this->user_id,
'create_time' => time()
];
//redis连接
$redis = $this->connectRedis();
//获取商品的库存总量
$goods_store_num = $redis->llen( $this->goods_store );
if( $goods_store_num > 0 ){
//用户已抢购成功
if( $redis->hGet($this->goods_rob_success, $this->user_id) ){
//记录重复抢购用户信息
RushLog::create($userinfo);
exit('您已抢购了哦');
//用户未抢购
}else{
//从商品库存队列减少库存
$count = $redis->lpop( $this->goods_store );
if( !$count ){
exit('库存不足');
//库存足够的情况下,才能抢购成功
}else{
//将抢购成功的用户信息插入到成功队列中
$redis->hSet($this->goods_rob_success, $this->user_id, serialize($userinfo));
//入库保存抢购信息
$userinfo = [
'user_id' => $this->user_id
];
$Rush = Rush::create($userinfo);
//入库失败
if( ! $Rush ){
exit('系统繁忙请重试');
}
}
}
//返回库存量
$goods_store_amount = $redis->llen( $this->goods_store );
//
echo json_encode(['code'=>1,'store'=>$goods_store_amount]);
//库存不足
}else{
//删除队列
$redis->del($this->user_store);
$redis->del($this->goods_store);
$redis->del($this->goods_rob_success);
//
exit('库存不足');
}
}
}
```