/** * 简单的内存缓存实现 * 适用于单实例部署,限制缓存大小和TTL * * 性能优化:减少数据库查询,提升响应速度 */ interface CacheItem { data: T expires: number } class SimpleCache { private cache = new Map>() private maxSize = 1000 // 最大缓存项数 private defaultTTL = 60000 // 默认TTL:1分钟 /** * 获取缓存 * @param key 缓存键 * @returns 缓存数据,如果过期或不存在则返回null */ get(key: string): T | null { const item = this.cache.get(key) if (!item) return null // 检查是否过期 if (Date.now() > item.expires) { this.cache.delete(key) return null } return item.data as T } /** * 设置缓存 * @param key 缓存键 * @param data 缓存数据 * @param ttl 生存时间(毫秒),默认1分钟 */ set(key: string, data: T, ttl: number = this.defaultTTL): void { // 如果缓存已满,删除最旧的项(FIFO) if (this.cache.size >= this.maxSize && !this.cache.has(key)) { const firstKey = this.cache.keys().next().value if (firstKey) { this.cache.delete(firstKey) } } this.cache.set(key, { data, expires: Date.now() + ttl, }) } /** * 删除缓存 * @param key 缓存键 */ delete(key: string): void { this.cache.delete(key) } /** * 清空所有缓存 */ clear(): void { this.cache.clear() } /** * 获取缓存大小 */ size(): number { return this.cache.size } /** * 清理过期项 */ cleanup(): void { const now = Date.now() // 使用 Array.from 避免迭代器兼容性问题 const entries = Array.from(this.cache.entries()) for (const [key, item] of entries) { if (now > item.expires) { this.cache.delete(key) } } } } // 单例实例 const cache = new SimpleCache() // 定期清理过期项(每5分钟) if (typeof setInterval !== 'undefined') { setInterval(() => { cache.cleanup() }, 5 * 60 * 1000) } export { cache, SimpleCache }