tp5基于redis实现商品秒杀

tp5通过redis实现秒杀

直接放代码

class Sellkill extends Controller
{

    private $goods_id = [68,69,70];  //这是要秒杀的商品

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    //将商品id对应的数量存入队列中
    public function add(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $goods_info = (new Goods())->where('id','in',$this->goods_id)->select()->toArray();
        foreach ($goods_info as $key=>$value){
           $store = $value['store_nums']; //商品库存
           for ($i=1;$i<=$store;$i++){
                $redis->lPush('sellkillGoodId:'.$value['id'],$i);
           }
           echo '商品'.$value['title'].'添加成功';
        }
        return '添加成功';
    }


    //抢购
    public function buy(Request $request){
        $goods_id = $request->param('goods_id');
        $user_id = $request->param('user_id');
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        if(!in_array($goods_id,$this->goods_id)){
            return json(['msg'=>'商品id错误','data'=>[]]);
        }
        $user_ids = $redis->sMembers('buyGoodsUserId'.$goods_id);
        if(in_array($user_id,$user_ids)){
            return json(['msg'=>'已拥有该商品','data'=>[]]);
        }
        if($redis->rPop('sellkillGoodId:'.$goods_id)){
            //将抢购到商品的用户添加到该商品对应的集合中
            $redis->sadd('buyGoodsUserId'.$goods_id,$user_id);
            //生成订单 减少商品数量等业务
            ......
            return json(['msg'=>'','data'=>'成功']);

        }else{
            return json(['msg'=>'抢购失败','data'=>[]]);
        }
    }
}

你可能感兴趣的:(php学习)