diff --git a/src/ws_server.php b/src/ws_server.php index 9d5e8e535..ee8d05bcb 100644 --- a/src/ws_server.php +++ b/src/ws_server.php @@ -13,9 +13,9 @@ require __DIR__ . '/vendor/autoload.php'; // 初始化ThinkPHP应用环境,加载配置和环境变量,主要用于数据库连接和其他配置 use think\App; -// 创建应用实例 +// 创建应用实例,传入应用根目录(src目录) // @intelephense-ignore-next-line -$app = new App(); +$app = new App(__DIR__); // 加载环境变量 if (is_file(__DIR__ . '/.env')) { @@ -31,6 +31,34 @@ if ($appEnv) { } } +// 初始化App实例(必须,否则Cache等组件无法获取配置) +// 这会加载配置文件,包括cache.php +if (!$app->initialized()) { + $app->initialize(); +} + +// 获取ThinkPHP Cache实例(三种方式任选其一) +// 方式1: 通过App实例直接访问(推荐,在CLI模式下最可靠) +$cache = $app->cache; + +// 方式2: 通过容器获取 +// $cache = $app->make('cache'); + +// 方式3: 使用Facade(在CLI模式下可能不可用,不推荐) +// use think\facade\Cache; +// Cache::get('key'); +// Cache::set('key', 'value', 3600); + +// Cache使用示例: +// $cache->get('key'); // 获取缓存 +// $cache->get('key', 'default'); // 获取缓存,不存在时返回默认值 +// $cache->set('key', 'value', 3600); // 设置缓存,有效期3600秒 +// $cache->has('key'); // 检查缓存是否存在 +// $cache->delete('key'); // 删除缓存 +// $cache->clear(); // 清空所有缓存 +// $cache->tag('tag_name')->set('key', 'value'); // 使用标签缓存 +// $cache->tag('tag_name')->clear(); // 清除标签下的所有缓存 + use Ratchet\App as RatchetApp; use Ratchet\ConnectionInterface; use Ratchet\MessageComponentInterface; @@ -51,11 +79,28 @@ use app\model\system\Addon; $addonDir = __DIR__ . '/addon'; $addonNames = []; -// 从数据库获取addon列表 +// 从数据库获取addon列表(使用Cache缓存,避免频繁查询数据库) +$cacheKey = 'websocket_addon_list'; +$cacheExpire = 300; // 缓存5分钟 + try { - $addon_model = new Addon(); - $addon_data = $addon_model->getAddonList([], 'name,status'); - $current_addons = $addon_data['data']; + // 尝试从缓存获取addon列表 + $cachedAddons = $cache->get($cacheKey); + + if ($cachedAddons !== null && !empty($cachedAddons)) { + echo "[WebSocket服务器] 从缓存获取插件列表\n"; + $current_addons = $cachedAddons; + } else { + echo "[WebSocket服务器] 从数据库获取插件列表\n"; + $addon_model = new Addon(); + $addon_data = $addon_model->getAddonList([], 'name,status'); + $current_addons = $addon_data['data']; + + // 将结果存入缓存 + $cache->set($cacheKey, $current_addons, $cacheExpire); + echo "[WebSocket服务器] 插件列表已缓存(有效期: {$cacheExpire}秒)\n"; + } + $db_addon_names = array_column($current_addons, 'name'); // 2. 从addon目录读取插件列表 @@ -218,6 +263,16 @@ class DefaultWebSocketController implements MessageComponentInterface $ratchetApp->route('/ws', new DefaultWebSocketController(), array('*')); echo "已注册默认WebSocket测试控制器到路径 /ws\n"; +// 缓存WebSocket服务器信息(可选,用于其他服务查询) +$serverInfoKey = 'websocket_server_info'; +$cache->set($serverInfoKey, [ + 'host' => $httpHost, + 'port' => $port, + 'address' => $address, + 'started_at' => date('Y-m-d H:i:s'), + 'registered_addons' => $registeredAddons +], 0); // 0表示永久缓存,直到手动删除 + echo "WebSocket服务器已启动,监听地址: ws://{$httpHost}:{$port}\n"; // 显示已注册WebSocket控制器的addon路径