<?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 '恭喜您!抢到了哦';
}
}
}
Laravel 高并发抢购模拟
Laravel框架
476
0
0
2022-05-01
标签
PHP高并发