redis模拟抢购

作者:谢高升 发布:2017-11-02 浏览:2219次

在thinkphp5.0框架使用redis,redis支持五种数据类型 string hash list set zset 

<?php
namespace app\index\controller;
use think\db;
class Index
{
    /**
     * 模拟商品的总库存
     */
    private $goods_count=100;
    private $redis;
    public function __construct(){
        $this->redis = $this->redisConnect();
    }
    /**
     * redis链接
     * @return \Redis
     */
    public function redisConnect(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        return $redis;
    }
    
    
    public function shop(){
        
        $msg = [];
        $uid = mt_rand(1000,9999);
        $len = $this->redis->HLEN('goods_users');
       // echo $len;exit;
        $goodsid = time();
        if($len<=$this->goods_count){
            // $this->redis->delete('goods_user_queue');exit;
            //判断用户是已经抢购了商品
            if(!($this->redis->hExists('goods_users','user_'.$uid))){
                $data= [
                    'user_'.$uid =>$uid,
                    'goodsid' =>$goodsid
                ];
                $this->redis->hset('goods_users','user_'.$uid,$uid);
                //如果没有抢到商品加入到队列
                $this->redis->lpush('goods_user_queue',json_encode($data));
                $msg['status']=1;
                $msg['msg'] = '恭喜你抢购成功';
            }else{
                $msg['status'] = 2;
                $msg['msg'] = 'sorry您已经购买过该商品了,只能参加一次';
            }
        }else{
            $msg['status'] = 3;
            $msg['msg'] = '活动已经结束';
        }
        echo json_encode($msg);
        
    }
    
    //跑定时任务
    public function insertdata(){
        $len = $this->redis->lLen('goods_user_queue');
        if($len){
            //如果redis存在购买信息则减少库存
            $datajson = $this->redis->lPop('goods_user_queue');
            $data = json_decode($datajson,true);
            $where['id'] = $data['goodsid'];
            //库存-1
            db('goods')->where($where)->update(['goodsnum'=>'goodsnum-1']);
            //写入订单表
            db('order')->insert(['goodsid'=>$data['goodsid'],'uid'=>$data['userid']]);
        }
    }
    
    
    
    
    
}




标签: redis