用PHP写了个网站压力测试工具

最后编辑时间: 2021-06-23

帮朋友新开发的系统做高并发压力测试,所以写了下面这些代码,仅供测试自己的网站,禁止非法使用,否则后果自负!

技术栈:使用了php的Swoole协程扩展,以及swoole的连接池,通过连接池来实现一次性请求的并发次数

使用方法

  • 将下载好的工具代码上传到服务器任意地方,然后全部解压出来,在根目录执行命令:php start.php,前提是你的php版本>=7.2,并且安装了swoole扩展(如果你是宝塔环境,可以在php扩展里面自行安装),执行了这段命令,下面的功能就可以正常使用了。
  • GET压力测试:http://服务器IP:9000/?url={请求URL地址}&action=get&time={压测时间}&num={并发数量}
  • POST压力测试:http://服务器IP:9000/?url={请求URL地址}&action=post&time={压测时间}&num={并发数量}&data={urlencode后的post数据}
  • 关闭工具,在服务器任意地方执行: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();

请在下方留下您的评论.加入TG吹水群