// 连接健康度校验文件 可从多个连接中筛选符合条件的链接并设置为全局连接 export const serviceList = [ { name: "API_INNER", baseUrl: process.env.VUE_APP_BASE_API_INNER || process.env.VUE_APP_BASE_API, // 内网地址, 没有的情况下,就使用外网地址 healthPath: "/Health", }, { name: "API_OUTER", baseUrl: process.env.VUE_APP_BASE_API, // 外网地址 healthPath: "/Health", }, ]; /** * 检测单个服务健康状态 * @param {Object} service - 服务配置(baseUrl + healthPath) * @returns {Promise} 可用的 baseUrl,失败返回 null */ export const checkServiceHealth = async (service) => { const { baseUrl, healthPath } = service; if (!baseUrl) return null; return new Promise(async (resolve, reject) => { try { // 健康检查请求(超时 3 秒,不携带 Token,避免未登录拦截) const response = await fetch(`${baseUrl}${healthPath}`, { method: "GET", timeout: 3000, headers: { "Content-Type": "application/json", }, }); if (response.ok) { console.log(`服务 ${service.name} 健康,地址:${baseUrl}`); resolve(baseUrl) // return baseUrl; } } catch (error) { console.error(`服务 ${service.name} 连接失败:`, error.message); resolve(null) // return null; } }) }; /** * 批量检测所有服务,返回第一个可用的 baseUrl * @returns {Promise} 可用的服务基础地址(失败则抛出异常) */ export const findAvailableService = async () => { // 并行检测所有服务(提高效率) const healthCheckPromises = serviceList.map((item) => { return checkServiceHealth(item) }); const healthResult = await Promise.any(healthCheckPromises); // 检测到健康的链接就立刻返回 // 筛选可用的 baseUrl const availableBaseUrl = healthResult if (availableBaseUrl) { return availableBaseUrl; } else { // 所有服务均不可用,抛出异常(后续在初始化时捕获) throw new Error("所有服务健康检查失败,请检查服务状态或网络配置"); } };