refactor: ♻️ 添加 websocket 开启控制,未配置 endpoint 不连接,单例控制 websocket 重复连接

This commit is contained in:
Ray.Hao
2025-04-29 23:37:13 +08:00
parent ea6323084c
commit 142d808a5e
4 changed files with 46 additions and 17 deletions

View File

@@ -1,12 +1,28 @@
import { useDictSync } from "@/hooks/websocket/services/useDictSync";
import { getAccessToken } from "@/utils/auth";
// 用于防止重复初始化的状态标记
let isInitialized = false;
/**
* 初始化WebSocket服务
*/
export function setupWebSocket() {
console.log("[WebSocketPlugin] 开始初始化WebSocket服务...");
// 检查是否已经初始化
if (isInitialized) {
console.log("[WebSocketPlugin] WebSocket服务已经初始化,跳过重复初始化");
return;
}
// 检查环境变量是否配置
const wsEndpoint = import.meta.env.VITE_APP_WS_ENDPOINT;
if (!wsEndpoint) {
console.log("[WebSocketPlugin] 未配置WebSocket端点,跳过WebSocket初始化");
return;
}
// 检查token是否存在
const token = getAccessToken();
if (!token) {
@@ -29,9 +45,11 @@ export function setupWebSocket() {
window.addEventListener("beforeunload", () => {
console.log("[WebSocketPlugin] 窗口即将关闭断开WebSocket连接");
dictWebSocket.closeWebSocket();
isInitialized = false;
});
console.log("[WebSocketPlugin] WebSocket服务初始化完成");
isInitialized = true;
}, 1000); // 延迟1秒初始化
} catch (error) {
console.error("[WebSocketPlugin] 初始化WebSocket服务失败:", error);