CacheManager.ts•1.09 kB
// 缓存管理器
class CacheManager {
private cache = new Map<string, { data: any; timestamp: number; ttl: number }>();
private maxSize = 100;
set(key: string, data: any, ttl: number = 300000): void { // 默认5分钟
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, {
data,
timestamp: Date.now(),
ttl
});
}
get(key: string): any | null {
const item = this.cache.get(key);
if (!item) return null;
if (Date.now() - item.timestamp > item.ttl) {
this.cache.delete(key);
return null;
}
return item.data;
}
clear(): void {
this.cache.clear();
}
cleanup(): void {
const now = Date.now();
for (const [key, item] of this.cache.entries()) {
if (now - item.timestamp > item.ttl) {
this.cache.delete(key);
}
}
}
}
export const cacheManager = new CacheManager();
// 自动清理过期缓存
setInterval(() => cacheManager.cleanup(), 60000); // 每分钟清理一次