Laravel 高併發搶購模擬

407593529發表於2021-06-21
<?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 協議》,轉載必須註明作者和本文連結

相關文章