'use strict'; const { Service } = require('egg'); /** 业务缓存 key 统一前缀(与邮箱验证码 oms:email:* 区分) */ const PREFIX = 'oms:cache'; /** 各类缓存的 key 构造器 */ const KEYS = { user: userId => `${PREFIX}:user:${userId}`, userPrincipals: userId => `${PREFIX}:user-principals:${userId}`, principalOptions: userId => `${PREFIX}:principal-options:${userId}`, principal: principalId => `${PREFIX}:principal:${principalId}`, }; /** * 业务缓存服务 * 缓存登录用户信息、用户可用主体列表、主体详情,避免高频请求反复查库。 * Redis 异常时全部降级为直接查库(只告警不抛错),保证可用性。 */ class CacheService extends Service { /** @return {Object} redis 客户端 */ get redis() { return this.app.redis; } /** @return {Object} 缓存有效期配置(秒) */ get ttls() { return this.config.cache; } /** * 读取缓存(Redis 异常时返回 null,降级为查库) * @param {String} key 缓存 key * @return {Promise} 缓存值,不存在为 null */ async read(key) { try { const raw = await this.redis.get(key); return raw ? JSON.parse(raw) : null; } catch (err) { this.logger.warn(`[cache] 读取失败,key=${key}:${err.message}`); return null; } } /** * 写入缓存(值为空时不写入,避免缓存穿透到空数据) * @param {String} key 缓存 key * @param {any} value 缓存值 * @param {Number} ttl 有效秒数 * @return {Promise} 无返回值 */ async write(key, value, ttl = 300) { if (value === null || value === undefined) return; try { await this.redis.set(key, JSON.stringify(value), 'EX', ttl); } catch (err) { this.logger.warn(`[cache] 写入失败,key=${key}:${err.message}`); } } /** * 删除若干 key * @param {Array} keys 缓存 key 列表 * @return {Promise} 无返回值 */ async forget(...keys) { const valid = keys.filter(Boolean); if (!valid.length) return; try { await this.redis.del(...valid); } catch (err) { this.logger.warn(`[cache] 删除失败,key=${valid.join(',')}:${err.message}`); } } /** * 按前缀批量删除(SCAN + DEL,用于“某类缓存全部失效”) * @param {String} prefix key 前缀 * @return {Promise} 无返回值 */ async forgetByPrefix(prefix) { try { let cursor = '0'; do { const [ next, keys ] = await this.redis.scan(cursor, 'MATCH', `${prefix}*`, 'COUNT', 200); cursor = next; if (keys && keys.length) await this.redis.del(...keys); } while (cursor !== '0'); } catch (err) { this.logger.warn(`[cache] 按前缀删除失败,prefix=${prefix}:${err.message}`); } } /** * 缓存优先取值:命中直接返回,未命中执行 loader 查库并回写缓存 * @param {String} key 缓存 key * @param {Number} ttl 有效秒数 * @param {Function} loader 未命中时的数据加载函数 * @return {Promise} 数据 */ async remember(key, ttl, loader) { const cached = await this.read(key); if (cached !== null) return cached; const value = await loader(); await this.write(key, value, ttl); return value; } // ---------- 用户信息 ---------- /** * 登录用户信息(不含 password / salt) * @param {Number} userId 用户ID * @return {Promise} 用户信息,不存在为 null */ async getUser(userId) { return await this.remember(KEYS.user(userId), this.ttls.user, async () => { const user = await this.ctx.model.User.findByPk(userId, { attributes: { exclude: [ 'password', 'salt' ] }, }); return user ? user.toJSON() : null; }); } // ---------- 用户与主体的关联 ---------- /** * 用户已绑定的主体ID列表(用于多租户数据隔离) * @param {Number} userId 用户ID * @return {Promise>} 主体ID数组 */ async getUserPrincipalIds(userId) { return await this.remember(KEYS.userPrincipals(userId), this.ttls.principal, async () => { const rows = await this.ctx.model.PrincipalUser.findAll({ where: { user_id: userId }, attributes: [ 'principal_id' ], }); return rows.map(row => Number(row.principal_id)); }); } /** * 用户可选主体列表(头部主体切换/下拉选择用,含该主体下的角色与默认标识) * @param {Number} userId 用户ID * @return {Promise>} 主体选项列表 */ async getUserPrincipalOptions(userId) { return await this.remember(KEYS.principalOptions(userId), this.ttls.principalOptions, async () => { const relations = await this.ctx.model.PrincipalUser.findAll({ where: { user_id: userId }, attributes: [ 'id', 'principal_id', 'role', 'is_default', 'status' ], order: [[ 'is_default', 'DESC' ], [ 'id', 'ASC' ]], }); if (!relations.length) return []; const principals = await this.ctx.model.Principal.findAll({ where: { id: relations.map(item => item.principal_id) }, attributes: [ 'id', 'name', 'type', 'status', 'contact_name', 'contact_phone' ], }); const principalMap = new Map(principals.map(item => [ Number(item.id), item ])); return relations.map(item => { const principal = principalMap.get(Number(item.principal_id)); if (!principal) return null; return { id: Number(principal.id), name: principal.name, type: principal.type, status: principal.status, contact_name: principal.contact_name, contact_phone: principal.contact_phone, role: item.role, is_default: item.is_default, relation_status: item.status, }; }).filter(Boolean); }); } // ---------- 主体信息 ---------- /** * 主体详情 * @param {Number} principalId 主体ID * @return {Promise} 主体信息,不存在为 null */ async getPrincipal(principalId) { return await this.remember(KEYS.principal(principalId), this.ttls.principal, async () => { const principal = await this.ctx.model.Principal.findByPk(principalId); return principal ? principal.toJSON() : null; }); } // ---------- 失效 ---------- /** * 用户资料/状态变更后失效:用户缓存 + 该用户的主体相关缓存 * @param {Number} userId 用户ID * @return {Promise} 无返回值 */ async invalidateUser(userId) { await this.forget( KEYS.user(userId), KEYS.userPrincipals(userId), KEYS.principalOptions(userId) ); } /** * 用户与主体的绑定关系变更后失效:主体ID列表 + 可选主体列表 * @param {Number} userId 用户ID * @return {Promise} 无返回值 */ async invalidateUserPrincipals(userId) { await this.forget(KEYS.userPrincipals(userId), KEYS.principalOptions(userId)); } /** * 主体新增/更新/删除后失效:主体详情 + 所有依赖主体信息的缓存 * (主体名称与状态变化会影响任意用户的可选主体列表,故按前缀整体失效) * @param {Number} principalId 主体ID * @return {Promise} 无返回值 */ async invalidatePrincipal(principalId) { await this.forget(KEYS.principal(principalId)); await this.forgetByPrefix(`${PREFIX}:principal-options:`); await this.forgetByPrefix(`${PREFIX}:user-principals:`); } } module.exports = CacheService;