美文网首页
laravel秒杀,抢购(redis)

laravel秒杀,抢购(redis)

作者: 杨森Janssen | 来源:发表于2018-02-12 15:06 被阅读278次

1.redis安装上安装步骤
2.配置好laravel Redis配置地址
我的2张数据简略表

create table s_order (
id int PRIMARY KEY AUTO_INCREMENT,
goods_number int unsigned,
goods_id int not null,
user_id int not null
);

create table s_goods (
id int primary key auto_increment,
name varchar(50) not null unique,
number int unsigned
);

insert into s_goods (name,number) value (
'秒杀商品1','15');
insert into s_goods (name,number) value (
'秒杀商品2','10');

3.第一步将商品存入redis队列中

public function storage(Request $request) 
{
    try {
        #查询商品
        // dd(Redis::keys('goods_store:*'));//查询有哪些队列
        //dd(Redis::lrange('goods_store:18', 0, '-1'));//查询队列的所有元素
        $goods_id = $request->get('goods_id');
        $resutl = DB::connection($this->connection)->table('s_goods')->where([
            'id' => $goods_id
        ])->select(['number','id'])->first();
        
        $store = $resutl->number;
        $res = Redis::llen('goods_store:' . $resutl->id);
        // dd($res);
        $count = $store - $res;
        for($i = 0;$i < $count; $i++){
            Redis::lpush('goods_store:' . $resutl->id, $resutl->id);
        }
        return 'success';
    } catch (\Exception $e) {
        throw $e;
    }
}

4.第二步,将访问的用户也存入redis队列

#将用户也存入队列中(就是将访问请求数据)(此处没有进行用户过滤,同一个用户进行多次请求也会进入队列)
   public function request_user($userid) 
   {
       $res=Redis::llen('user_list');
       #判断排队数
       #判断队列数(防止队列数据过大,redis服务器炸掉)
       if ($res=Redis::llen('user_list') > 1000) {
           // return '排队数大于商品总数';
           return false;
       }
       #添加数据
       Redis::lpush('user_list', $userid);
       return true;    
   }

5.设置文件锁(单一处理的思想)

#使用文件锁flock()
    #原理使用模拟使用文件操作,当flock_order()程序未运行完毕时,就是$fp未关闭,再次运行flock_order(),flock($fp, LOCK_EX | LOCK_NB)则会返回flase,
    #从而达到我们的需求
    public function flock_order() 
    {
        try {
            $fp = fopen(base_path(). '/public/my/lock.txt', 'w+');
            if(!flock($fp, LOCK_EX | LOCK_NB)) {
                // sleep(30); 等待30秒,测试用
                // echo '系统繁忙请稍后重试';
                return [
                    'code' => '0',
                    'data' => $fp
                ];
            }
            return [
                'code' => '1',
                'data' => $fp
            ];;
        } catch (\Exception $e) {
            throw $e;
        }
    }

6.设置数据库事务悲观锁

#生成订单
    #采用数据库事务的悲观锁
    public function store_order($user_id, $goods_id, $number)
    {
        try {
            #开启事务
            DB::beginTransaction();
            #查询库存sharedLock()共享锁,可以读取到数据,事务未提交不能修改,直到事务提交
            #lockForUpdate()不能读取到数据
            $resutl = DB::connection($this->connection)->table('s_goods')->where([
                     'id' => $goods_id
            ])->select('number')->lockForUpdate()->first()->number;
            // dd($resutl);
            #添加订单
            if ( $resutl ) {
                $resutl_order = DB::connection($this->connection)->table($this->table)->insert([
                    'user_id' => $user_id,
                    'goods_id' => $goods_id,
                    'goods_number' => $number
                ]);
                #减少库存
                $resutl_update = DB::connection($this->connection)->table('s_goods')->where(
                    [
                        'id' => $goods_id
                    ]
                )->decrement('number', $number);
                if ($resutl_order > 0 && $resutl_update > 0) {
                    DB::commit();
                    return 1;
                }
            }

            DB::rollBack();
            return 0;
            
        } catch(\Exception $e) {
            throw $e;
        }
    }

7最后就是抢购入口了

 #实现秒杀(通过100线程的并发测试)
    public function seconds_kill(Request $request) 
    {
        try {
            $user_data = $request->only(['user_id', 'goods_id']);
            if ( !$user_data ) {
                return '数据不能为空';
            }
            #访问用户入队接口
            $user_list = $this->request_user($user_data['user_id']);
            
            if ( !$user_list ) {
                return '排队数大于商品总数';
            }

            #进入文件锁(访问文件锁接口)(有return 一定要有关闭文件的操作)
            $file_flock = $this->flock_order();
            if ( !$file_flock['code'] ) {
                fclose($file_flock['data']);
                return '访问人数多,请稍后重试';
            }

            // $goods = Redis::lrange('goods_store', 0, '-1');  查询所有商品
            #消费商品,从队列中取出商品
            $count= Redis::lpop('goods_store:' . $user_data['goods_id']);
            if(!$count){
                // dd('商品抢光了');
                fclose($file_flock['data']);
                return '商品抢光了';
            }
            #将用户从队列里面弹出(先进先出,存的时候用的lpush,所以取应该rpop)
            $userid = Redis::rpop('user_list');

            
            #最后进入数据库操作(每次固定消费1个)
            $mysql_data = $this->store_order($userid, $count, '1');

            if ( !$mysql_data ) {
                fclose($file_flock['data']);
                return '生成订单失败';
            }
            #关闭文件(最后成功一定要关闭文件)
            fclose($file_flock['data']);
            return '抢购成功';
            #生成订单
        } catch (\Exception $e) {
            throw $e;
        }
    }

8.测试工具下载地址
下载这个

image.png

如果你有更好的处理抢购问题,一起交流交流

相关文章

网友评论

      本文标题:laravel秒杀,抢购(redis)

      本文链接:https://www.haomeiwen.com/subject/gygrtftx.html