帮朋友新开发的系统做高并发压力测试,所以写了下面这些代码,仅供测试自己的网站,禁止非法使用,否则后果自负!
技术栈:使用了php的Swoole协程扩展,以及swoole的连接池,通过连接池来实现一次性请求的并发次数
php start.php
,前提是你的php版本>=7.2,并且安装了swoole扩展(如果你是宝塔环境,可以在php扩展里面自行安装),执行了这段命令,下面的功能就可以正常使用了。kill -9 $(ps -ef|grep test|gawk '$0 !~/grep/ {print $2}' |tr -s '\n' ' ')
//修改当前文件资源上限
shell_exec("ulimit -n 100960");
$http = new Swoole\Http\Server("0.0.0.0", 9000, SWOOLE_BASE);
$http->on("start", function (\Swoole\Http\Server $server) {
swoole_set_process_name("test");
echo "start success!\n";
});
$http->set(['daemonize' => 1]);
$http->on("request", function (\Swoole\Http\Request $request, \Swoole\Http\Response $response) {
$response->header("Content-Type", "text/plain");
$url = (string)$request->get['url'];
$action = strtolower((string)$request->get['action']);
$time = (int)$request->get['time'] + time(); //如果这个小于了当前时间表示过期了
$num = (int)$request->get['num'];
$data = urldecode((string)$request->get['data']);
if ($action != "get" && $action != "post") {
$response->end("action error");
return;
}
\Swoole\Coroutine::create(function () use ($data, $action, $num, $url, $time) {
$connectionPool = new \Swoole\ConnectionPool(function () use ($url, $time) {
return new Request($url);
}, $num);
$connectionPool->fill();
$i = 1;
while (true) {
if ($time < time()) {
$connectionPool->close();
break;
}
$request = $connectionPool->get();
if ($request instanceof Request) {
\Swoole\Coroutine::create(function () use ($data, $action, $connectionPool, $i, $request) {
try {
if ($action == 'get') {
$request->get();
} else if ($action == 'post') {
$request->post($data);
}
$connectionPool->put($request);
} catch (Exception $e) {
$connectionPool->put($request);
}
});
}
$i++;
}
});
$message = sprintf('stress tests url:%s - thread:%s - expire:%s', $url, $num, date("Y/m/d H:i:s", $time));
@$response->end((string)$message);
});
$http->start();