压测工具如下:
<?php
use Swoole\Coroutine\Channel;
use Swoole\Coroutine\Http\Client;
/**
* Created by PhpStorm.
* User: randy
* Date: 2021/3/11
*/
class Benchmark
{
private static $concurrentInfo = [];
/**
* 本轮压测持续时长,单位: 秒
* @var integer
*/
private $duration;
public function __construct($duration)
{
$this->duration = $duration;
}
/**
* 添加要并发压测的接口
* @param string $uri eg: /user/profile/self
* @param int $clientNum 并发的客户端数量
* @param callable $func
* @return $this
*/
public function addConcurrentApi(string $uri, int $clientNum, callable $func)
{
$pool = new Channel($clientNum);
for ($i = 0; $i < $clientNum; $i++) {
$cli = new Client("192.168.66.210", 9501);
$pool->push($cli);
}
self::$concurrentInfo[$uri] = [
'client' => $pool,
'func' => $func
];
return $this;
}
public function run()
{
$finishTime = time() + $this->duration;
foreach (self::$concurrentInfo as $uri => $item) {
/** @var Channel $chan */
$chan = $item['client'];
$func = $item['func'];
go(function () use ($uri, $chan, $func, $finishTime) {
$callTimes = 0;
$begin = microtime(true);
while (time() < $finishTime) {
$cli = $chan->pop();
go(function () use ($chan, $cli, $func) {
defer(function () use ($chan, $cli) {
$chan->push($cli);
});
call_user_func($func, $cli);
});
$callTimes++;
}
$qps = (int)($callTimes / (microtime(true) - $begin));
echo str_pad("{$uri}", 20) . "QPS: $qps\n";
});
}
}
}
//Usage:
go(function () {
//此处压测持续时长10秒
$benchmark = new Benchmark(10);
//此处开始添加自己的api压测脚本
$benchmark->addConcurrentApi("/user/login", 2000, function ($cli) {
$cli->get("/demo");
$body = $cli->body;
// echo $body . PHP_EOL;
});
//可以不断加接口$benchmark->addConcurrentApi
$benchmark->run();
});
压测结果如下:
[root@localhost ~]# php benchmark.php
/user/login QPS: 19146