diff --git a/backend/server.js b/backend/server.js index feeb459..b720b78 100644 --- a/backend/server.js +++ b/backend/server.js @@ -63,9 +63,91 @@ const upload = multer({ limits: { fileSize: 5 * 1024 * 1024 * 1024 } // 5GB限制 }); -// 分享文件信息缓存(内存缓存) -// 格式: Map -const shareFileCache = new Map(); +// ===== TTL缓存类 ===== + +// 带过期时间的缓存类 +class TTLCache { + constructor(defaultTTL = 3600000) { // 默认1小时 + this.cache = new Map(); + this.defaultTTL = defaultTTL; + + // 每10分钟清理一次过期缓存 + this.cleanupInterval = setInterval(() => { + this.cleanup(); + }, 10 * 60 * 1000); + } + + set(key, value, ttl = this.defaultTTL) { + const expiresAt = Date.now() + ttl; + this.cache.set(key, { value, expiresAt }); + } + + get(key) { + const item = this.cache.get(key); + if (!item) { + return undefined; + } + + // 检查是否过期 + if (Date.now() > item.expiresAt) { + this.cache.delete(key); + return undefined; + } + + return item.value; + } + + has(key) { + const item = this.cache.get(key); + if (!item) { + return false; + } + + // 检查是否过期 + if (Date.now() > item.expiresAt) { + this.cache.delete(key); + return false; + } + + return true; + } + + delete(key) { + return this.cache.delete(key); + } + + // 清理过期缓存 + cleanup() { + const now = Date.now(); + let cleaned = 0; + + for (const [key, item] of this.cache.entries()) { + if (now > item.expiresAt) { + this.cache.delete(key); + cleaned++; + } + } + + if (cleaned > 0) { + console.log(`[缓存清理] 已清理 ${cleaned} 个过期的分享缓存`); + } + } + + // 获取缓存大小 + size() { + return this.cache.size; + } + + // 停止清理定时器 + destroy() { + if (this.cleanupInterval) { + clearInterval(this.cleanupInterval); + } + } +} + +// 分享文件信息缓存(内存缓存,1小时TTL) +const shareFileCache = new TTLCache(60 * 60 * 1000); // ===== 工具函数 =====