webman的HTTP进程,设置为8
个进程提供服务;
在 http进程启动后,执行 onWorkerStart
方法时,建立与gatewayWorker 的 ws
连接。
故障现象是:有1-2个进程的链接立刻建立成功 onMessage
收到信息;而 余下的 N个进程,要卡顿很久才能收到 来自 ws 的 onMessage
消息。
百思不得其解,望各位大佬赐教,感谢。
<?php
namespace app\process;
use GatewayWorker\Lib\Gateway;
use support\Log;
use Throwable;
use Webman\App;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Timer;
class Http extends App
{
/**
* OnWorkerStart.
* @param $worker
* @return void
*/
public function onWorkerStart($worker): void
{
static::$worker = $worker;
\Workerman\Protocols\Http::requestClass(static::$requestClass);
// 连接 GatewayWorker gateway进程的 ws服务
$connection = new AsyncTcpConnection('ws://iyuu.net/websocket');
$connection->onMessage = function (AsyncTcpConnection $connection, $data) {
// ----------------------------------------这里有几个连接会卡很久----------------------------------------
Log::debug('onMessage: ' . $data);
// 忽略pong
if ('pong' === $data) {
return;
}
// 解析数据
$decode = json_decode($data, true);
if (empty($decode)) {
return;
}
// 获取事件
if ($event = $decode['event'] ?? '') {
if ('init' === $event) {
$client_id = $decode['client_id'] ?? '';
Log::debug('onWorkerStart异步连接初始化:' . $client_id . ' ' . App::worker()->id);
Gateway::bindUid($client_id, 'webman_system');
}
} else {
// HTTP响应 Chunk
}
};
$connection->onClose = function (AsyncTcpConnection $connection) {
$connection->reConnect(3);
};
Timer::add(30, function () use ($connection) {
try {
$connection->send('ping');
} catch (Throwable $throwable) {
Log::error('onWorkerStart异步连接PING异常:' . $throwable->getMessage());
}
});
$connection->connect();
}
}
代码简化后,如下所示