feat: 添加状态监控插件和Redis原子操作支持

- 新增 `/status` 指令,展示机器人运行状态和系统指标
- 实现Redis Lua脚本支持原子化计数器操作
- 添加消息收发统计功能
- 完善文档,包括插件开发和性能优化指南
- 重构WebSocket连接池,增加健康检查机制
- 移除旧版编译脚本,优化项目结构
This commit is contained in:
2026-01-23 15:54:45 +08:00
parent 489dd8c77d
commit d458413e4b
28 changed files with 1529 additions and 1177 deletions

View File

@@ -7,7 +7,7 @@ WebSocket 连接池模块
import asyncio
import websockets
from websockets.legacy.client import WebSocketClientProtocol
from typing import Optional, Dict, Any, cast
from typing import Optional, Dict, Any, cast, Union
import uuid
from loguru import logger
@@ -28,7 +28,7 @@ class WSConnection:
self.is_active = True
self._pending_requests: Dict[str, asyncio.Future] = {}
async def send(self, data: dict):
async def send(self, data: Union[Dict[Any, Any], bytes]):
"""
发送数据到 WebSocket 连接
"""
@@ -57,6 +57,19 @@ class WSConnection:
self.is_active = False
raise WebSocketError(f"接收数据失败: {e}")
async def ping(self, timeout: int = 5) -> bool:
"""
对 WebSocket 连接执行 ping-pong 健康检查
"""
if not self.is_active:
return False
try:
await asyncio.wait_for(self.conn.ping(), timeout=timeout)
return True
except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed):
self.is_active = False
return False
async def close(self):
"""
关闭 WebSocket 连接
@@ -132,7 +145,7 @@ class WSConnectionPool:
async def get_connection(self) -> WSConnection:
"""
从连接池获取一个连接
从连接池获取一个健康的连接,包含健康检查。
"""
if self._closed:
raise WebSocketError("连接池已关闭")
@@ -141,18 +154,21 @@ class WSConnectionPool:
# 尝试从连接池获取连接
conn = await asyncio.wait_for(self.pool.get(), timeout=5)
# 检查连接是否活跃
if not conn.is_active:
logger.warning(f"连接 {conn.conn_id} 已失效,重新创建")
return await self._create_connection()
return conn
# 健康检查
if await conn.ping():
logger.debug(f"连接 {conn.conn_id} 健康检查通过")
return conn
else:
logger.warning(f"连接 {conn.conn_id} 健康检查失败,丢弃并获取新连接")
await conn.close()
return await self.get_connection() # 递归获取下一个
except asyncio.TimeoutError:
# 连接池为空,创建新连接
logger.warning("连接池为空,创建临时连接")
logger.warning("连接池在5秒内无可用连接,创建连接")
return await self._create_connection()
except Exception as e:
raise WebSocketError(f"获取连接失败: {e}")
raise WebSocketError(f"获取连接时发生未知错误: {e}")
async def release_connection(self, conn: WSConnection):
"""