Laravel 高并发抢购模拟

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class TestController extends Controller
{
    public function index()
    {
        // 设置库存到redis里
        //$this->setStock();

        // 抢购
        //$this->buy();

        /*$strs     = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        $userName = substr(str_shuffle($strs), mt_rand(0, strlen($strs) - 11), 10);
        DB::table('test')->insert(['user_name' => $userName]);
        echo $userName;*/

    }

    /**
     * 设置库存到redis里
     */
    public function setStock()
    {
        // 查询商品信息
        $goods = DB::table('goods')->where('id', 1)->first();


        $len = Redis::llen('goods_store:1');         // 检查库存,goods_store:1 定义为健名

        $count = $goods->goods_count - $len;            // 实际库存-被抢购的库存 = 剩余可用库存
        for ($i = 0; $i < $count; $i++) {
            Redis::lpush('goods_store:1', 1);// 往goods_store列表中,未抢购之前这里应该是默认滴push10个库存数了
        }

        //echo \Redis::llen('goods_store:1');//未抢购之前这里就是10了
    }

    /**
     * 模拟抢购
     */
    public function buy()
    {
        $strs     = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        $userName = substr(str_shuffle($strs), mt_rand(0, strlen($strs) - 11), 10);

        /* 模拟抢购操作,抢购前判断redis队列库存量 */
        $count = Redis::lpop('goods_store:1');
        if (!$count) {
            echo '已经抢光了哦';
            exit;
        }

        $result = Redis::lpush('order:1', $userName);
        if ($result) {
            echo '恭喜您!抢到了哦';
        }

    }

}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!