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

免职说明

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

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

使用说明

  • php版本>=7.2,并且安装了swoole扩展(如果你是宝塔环境,可以在php扩展里面自行安装)
  • 下载好的工具代码上传到服务器任意地方,然后全部解压出来
  • 在根目录执行命令php start.php
  • 关闭工具,在服务器任意地方执行: kill -9 (ps -ef|grep test|gawk '0 !~/grep/ {print
代码语言:javascript
复制
请求方法:
GET压力测试:http://服务器IP:9000/?url={请求URL地址}&action=get&time={压测时间}&num={并发数量}
POST压力测试:http://服务器IP:9000/?url={请求URL地址}&action=post&time={压测时间}&num={并发数量}&data={urlencode后的post数据}
代码语言:javascript
复制
//修改当前文件资源上限
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-&gt;post(data);
}
connectionPool-&gt;put(request);
} catch (Exception $e) {
connectionPool-&gt;put(request);
}
});
}
$i++;
}
});
message = sprintf(&#39;stress tests url:%s - thread:%s - expire:%s&#39;, url, num, date(&#34;Y/m/d H:i:s&#34;, time));
@response-&gt;end((string)message);
});

$http->start();