tp 5はredisに基づいて商品の秒殺を実現する

15320 ワード

tp 5 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'=>[]]);
        }
    }
}