import EventEmitter from 'events'; /** * 全局缓存类 * 使用单例模式实现的带过期时间的键值对存储 */ class GlobalCache extends EventEmitter { constructor() { super(); if (GlobalCache.instance) { return GlobalCache.instance; } // 存储数据的 Map this.cache = new Map(); // 存储定时器的 Map this.timers = new Map(); GlobalCache.instance = this; } /** * 设置缓存值 * @param {string} key - 键 * @param {*} value - 值 * @param {number} [expireTime=0] - 过期时间(秒),0表示永不过期 * @returns {*} 设置的值 */ set(key, value, expireTime = 0) { if (typeof key !== 'string') { throw new Error('Key must be a string'); } // 如果该key已存在,清除之前的定时器 if (this.timers.has(key)) { clearTimeout(this.timers.get(key)); this.timers.delete(key); } // 存储值 this.cache.set(key, value); // 如果设置了过期时间 if (expireTime > 0) { const timer = setTimeout(() => { this.delete(key); this.emit('expired', key); // 触发过期事件 }, expireTime * 1000); // 存储定时器 this.timers.set(key, timer); } return value; } /** * 获取缓存值 * @param {string} key - 键 * @returns {*} 值,如果不存在或已过期返回null */ get(key) { if (typeof key !== 'string') { throw new Error('Key must be a string'); } return this.cache.has(key) ? this.cache.get(key) : 0; } /** * 删除缓存值 * @param {string} key - 键 * @returns {boolean} 是否成功删除 */ delete(key) { if (this.timers.has(key)) { clearTimeout(this.timers.get(key)); this.timers.delete(key); } return this.cache.delete(key); } /** * 清除所有缓存 */ clear() { // 清除所有定时器 for (const timer of this.timers.values()) { clearTimeout(timer); } this.timers.clear(); this.cache.clear(); } /** * 获取所有缓存的键 * @returns {string[]} 键数组 */ keys() { return Array.from(this.cache.keys()); } /** * 获取缓存数量 * @returns {number} 缓存数量 */ size() { return this.cache.size; } /** * 检查键是否存在 * @param {string} key - 键 * @returns {boolean} 是否存在 */ has(key) { return this.cache.has(key); } } // 导出单例实例 export const globalCache = new GlobalCache();