swoole怎么提升服务器性能,利用 Swoole 的 Channel 测试 Websocket 异步服务器性能

本文展示了如何在Docker环境下利用Swoole协程WebSocket客户端进行高并发测试。通过创建协程并连接到服务器,发送并接收WebSocket消息,测试结果显示在不同运行中,每秒请求数在1446到2145之间,平均响应时间在2.3307秒到3.4571秒,表明Swoole协程能有效提升并发处理能力。
摘要由CSDN通过智能技术生成

环境使用 Docker:

服务器端使用前面文章中的代码:

测试程序代码:<?php

use Swoole\Coroutine\Channel;

use Swoole\Coroutine\Http\Client;

use function Swoole\Coroutine\run;

class Test

{

protected $request; //总请求量

protected $requested = 0;

protected $start_time;

protected $channel;

function __construct()

{

$this->request = 5000;

$this->channel = new Channel($this->request);

}

public function run()

{

$this->start_time = microtime(true);

$this->webSocket();

}

protected function webSocket()

{

// 创建一个协程容器

run(function () {

for ($i = 0; $i < $this->request; $i++) {

// 开启一个协程

go(function() use ($i) {

$cli = new Client('127.0.0.1', 8081);

$cli->set(['websocket_mask' => false]);

$ret = $cli->upgrade('/');

if ($ret) {

$ret = $cli->push('1 Hello World');

$this->channel->push([$i => $cli->recv(1)]);

}

});

}

$this->finish();

});

}

protected function finish()

{

for ($i = 1; $i <= $this->request; $i++) {

$this->channel->pop();

$this->requested++;

}

$cost_time = round(microtime(true) - $this->start_time, 4);

echo "Request num:" . $this->request.PHP_EOL;

echo "Success num:" . $this->requested.PHP_EOL;

echo "Total time:" . $cost_time.PHP_EOL;

echo "Request per second:" . intval($this->request / $cost_time).PHP_EOL;

}

}

$test = new Test();

$test->run();

测试结果:root@37a5ad8c277a:/var/www/project-1# php web/client.php

Request num:5000

Success num:5000

Total time:2.9934

Request per second:1670

root@37a5ad8c277a:/var/www/project-1# php web/client.php

Request num:5000

Success num:5000

Total time:3.4571

Request per second:1446

root@37a5ad8c277a:/var/www/project-1# php web/client.php

Request num:5000

Success num:5000

Total time:2.6804

Request per second:1865

root@37a5ad8c277a:/var/www/project-1# php web/client.php

Request num:5000

Success num:5000

Total time:2.8765

Request per second:1738

root@37a5ad8c277a:/var/www/project-1# php web/client.php

Request num:5000

Success num:5000

Total time:2.3307

Request per second:2145

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值