```
<?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('庫存不足');
}
}
}
```