'use strict'; const { Service } = require('egg'); class CacheService extends Service { get redis() { return this.app.redis; } get prefix() { return this.config.cache.prefix; } /** 统一拼 key,避免不同业务互相覆盖 */ key(name) { return this.prefix ? `${this.prefix}${name}` : name; } /** * Redis 不可用时降级(返回 fallback),不阻塞主流程: * 缓存只是旁路,读不到就回源,写不进去也只是少一次缓存 */ async _call(action, fallback) { if (!this.app.redis) return fallback; try { return await action(); } catch (err) { this.ctx.logger.warn('[cache] redis 异常,已降级: %s', err.message); return fallback; } } /** 读取并自动 JSON 反序列化,未命中返回 null */ async get(name) { const raw = await this._call(() => this.redis.get(this.key(name)), null); if (raw === null || raw === undefined) return null; try { return JSON.parse(raw); } catch (err) { // 不是 JSON 就按字符串返回 return raw; } } /** 写入,ttl 单位秒;ttl <= 0 表示永不过期 */ async set(name, value, ttl = this.config.cache.ttl) { const raw = typeof value === 'string' ? value : JSON.stringify(value); const key = this.key(name); if (ttl > 0) return this._call(() => this.redis.setex(key, ttl, raw), 'OK'); return this._call(() => this.redis.set(key, raw), 'OK'); } async del(name) { return this._call(() => this.redis.del(this.key(name)), 0); } async ttl(name) { return this._call(() => this.redis.ttl(this.key(name)), -2); } /** 计数器,可用于限流、统计等场景(Redis 不可用时抛出,不做降级) */ async incr(name, ttl) { const key = this.key(name); const value = await this.redis.incr(key); if (ttl > 0 && value === 1) { await this.redis.expire(key, ttl); } return value; } /** * 缓存旁路(cache-aside):命中直接返回,未命中回源并写入缓存 * loader 返回 null/undefined 时不写缓存 */ async remember(name, ttl, loader) { const cached = await this.get(name); if (cached !== null) return cached; const value = await loader(); if (value === null || value === undefined) return value; await this.set(name, value, ttl); return value; } } module.exports = CacheService;