/**
* 改良版 利用swoole的Channel通道* 协程下 秒杀案例(5000次请求 并发1000) ab -n 5000 -c 1000 http://192.168.99.100:9555/order/skill
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
public function skill()
{
$container = ApplicationContext::getContainer();
$redis = $container->get(Redis::class);
co(function () use ($redis) {
$chan = new Channel(1);
co(function () use ($chan, $redis) {
$key = 'sku_id';
$count = $redis->lPop($key);
$chan->push($count);
});
co(function () use ($chan, $redis) {
$chanData = $chan->pop();
if (!$chanData) {
$this->log('库存为0,已售罄', 0);
} else {
$sku_id = 11;
// 插入订单
$order_sn = getIdGenerator();
$data = [
'order_sn' => $order_sn,
'user_id' => 1,
'goods_id' => 1,
'sku_id' => 11,
'price' => 10
];
$sql2 = "update mall_test_store set number=number-1 where sku_id='{$sku_id}'";
if (Db::table('test_order')->insert($data) && DB::update($sql2)) {
$this->log('下单成功', 1);
} else {
$this->log('下单失败', -1);
}
}
});
});
}
// 设置redis
private function setkey($key, $count)
{
$container = ApplicationContext::getContainer();
$redis = $container->get(Redis::class);
for ($i = 0; $i < $count; $i++) {
$redis->lPush($key, 1);
}
}
//记录日志
private function log($event, $type = 0)
{
$sql = "insert into mall_test_log(event,type)values('{$event}','{$type}')";
Db::insert($sql);
var_dump($event);
}
// 初始化所有变量
public function clean()
{
$sku_id = 11;
Db::delete("truncate table mall_test_log");
Db::delete("truncate table mall_test_order");
Db::update("update mall_test_store set number=1000 where sku_id='{$sku_id}'");
// 在redis中设置一下sku的数量。
$this->setkey('sku_id', 1000);
}