1.重构websocket连接
This commit is contained in:
@@ -10,6 +10,8 @@ use Throwable;
|
||||
|
||||
/**
|
||||
* 通过 Redis 列表在不同进程间投递 WebSocket 事件。
|
||||
*
|
||||
* 入队失败统一返回 false 并写 ws 日志(runtime/logs/ws.log),便于排查"为什么没有推送"。
|
||||
*/
|
||||
final class GameWebSocketEventBus
|
||||
{
|
||||
@@ -18,7 +20,7 @@ final class GameWebSocketEventBus
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return bool 是否成功入队(false 表示 Redis 不可用或参数非法,调用方应避免标记“已推送”)
|
||||
* @return bool 是否成功入队(false 表示 Redis 不可用或参数非法,调用方应避免标记"已推送")
|
||||
*/
|
||||
public static function publish(string $topic, array $data): bool
|
||||
{
|
||||
@@ -34,12 +36,34 @@ final class GameWebSocketEventBus
|
||||
];
|
||||
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($json) || $json === '') {
|
||||
Log::channel('ws')->warning('publish skip: invalid json payload', [
|
||||
'topic' => $topic,
|
||||
]);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$len = Redis::lPush(self::KEY_QUEUE, $json);
|
||||
return is_numeric($len) && (int) $len > 0;
|
||||
$ok = is_numeric($len) && (int) $len > 0;
|
||||
if ($ok) {
|
||||
$uid = filter_var($data['user_id'] ?? 0, FILTER_VALIDATE_INT);
|
||||
Log::channel('ws')->info('publish', [
|
||||
'topic' => $topic,
|
||||
'user_id' => $uid === false ? 0 : (int) $uid,
|
||||
'queue_len_after' => (int) $len,
|
||||
'payload_size' => strlen($json),
|
||||
]);
|
||||
} else {
|
||||
Log::channel('ws')->warning('publish lpush returned non-positive', [
|
||||
'topic' => $topic,
|
||||
'returned' => $len,
|
||||
]);
|
||||
}
|
||||
return $ok;
|
||||
} catch (Throwable $e) {
|
||||
Log::channel('ws')->error('publish failed (redis exception)', [
|
||||
'topic' => $topic,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
Log::warning('ws event bus publish failed', [
|
||||
'topic' => $topic,
|
||||
'error' => $e->getMessage(),
|
||||
@@ -92,10 +116,27 @@ final class GameWebSocketEventBus
|
||||
'server_time' => $serverTime,
|
||||
];
|
||||
}
|
||||
} catch (Throwable) {
|
||||
} catch (Throwable $e) {
|
||||
Log::channel('ws')->error('popBatch failed (redis exception)', [
|
||||
'error' => $e->getMessage(),
|
||||
'popped' => count($out),
|
||||
]);
|
||||
return $out;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前队列堆积长度(监控用)。
|
||||
*/
|
||||
public static function queueLength(): int
|
||||
{
|
||||
try {
|
||||
$len = Redis::lLen(self::KEY_QUEUE);
|
||||
return is_numeric($len) ? (int) $len : 0;
|
||||
} catch (Throwable) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user