记录学习与后端知识并分享学习代码过程(会飞的鱼Blog)

如何用PHP写网站压力测试工具

会飞的鱼 0 2287 2021年1月23日

免职说明

  • 该文章请以学习的角度以及系统做高并发压力测试进行阅读。
  • 请勿使用本代码对任何网站做压力测试以及恶意攻击。
  • 仅供测试自己的网站,禁止非法使用,否则后果自负!

该压力测试工具使用了php的Swoole协程扩展,以及swoole的连接池,通过连接池来实现一次性请求的并发次数。仅供测试自己的网站,禁止非法使用,否则后果自负!

使用说明

  • php版本>=7.2,并且安装了swoole扩展(如果你是宝塔环境,可以在php扩展里面自行安装)
  • 下载好的工具代码上传到服务器任意地方,然后全部解压出来
  • 在根目录执行命令php start.php
  • 关闭工具,在服务器任意地方执行: kill -9 $(ps -ef|grep test|gawk '$0 !~/grep/ {print $2}' |tr -s '\n' ' ')
请求方法:
GET压力测试:http://服务器IP:9000/?url={请求URL地址}&action=get&time={压测时间}&num={并发数量}
POST压力测试:http://服务器IP:9000/?url={请求URL地址}&action=post&time={压测时间}&num={并发数量}&data={urlencode后的post数据}
//修改当前文件资源上限
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();
本文由 @会飞的鱼 于 2021-1-23 发布在 会飞的鱼Blog,如无特别说明,本博文章均为原创,转载请保留出处。

网友评论

    暂无评论

会飞的鱼 V

一条会飞的鱼!

745 文章
7274 评论
1071 万 阅读
8年 博龄
最新文章
最新评论
嘻嘻嘻
2个月前 (2024-03-19)

ThinkPHP实现用户注册、登录模块

标签

会飞的鱼 在线咨询

在线时间:9:00-22:00
周六、周日:14:00-22:00