基于swoole开发一个类似ab的压测工具

3 篇文章 0 订阅

压测工具如下:

<?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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值