class Cache<T, K> {
private cache: Map<K, { value: T; expiration: number }>;
private timer: Map<K, NodeJS.Timeout>;
constructor() {
this.cache = new Map();
this.timer = new Map();
}
set(key: K, value: T, expiration: number): void {
const currentTime = Date.now();
const expirationTime = currentTime + expiration;
this.cache.set(key, { value, expiration: expirationTime });
if (this.timer.has(key)) {
clearTimeout(this.timer.get(key) as NodeJS.Timeout);
}
const timeout = setTimeout(() => {
this.cache.delete(key);
this.timer.delete(key);
}, expiration);
this.timer.set(key, timeout);
}
get(key: K): T | null {
const cached = this.cache.get(key);
if (cached) {
const currentTime = Date.now();
if (currentTime < cached.expiration) {
return cached.value;
} else {
this.cache.delete(key);
if (this.timer.has(key)) {
clearTimeout(this.timer.get(key) as NodeJS.Timeout);
this.timer.delete(key);
}
return null;
}
}
return null;
}
}
设计思路
- 数据存储:使用
Map
来存储键值对,这样可以方便地根据键获取值,并且Map
的查找时间复杂度为O(1)。
- 过期机制:为每个缓存项记录过期时间,每次设置缓存时更新过期时间,并设置一个定时器,在过期时自动删除缓存项。
- 内存优化:通过定时器在数据过期后自动清理缓存,避免无效数据占用内存。
性能瓶颈及优化方向
- 性能瓶颈:
- 定时器管理:如果缓存项非常多,定时器的创建和管理可能会消耗大量资源,影响性能。
- 过期检查:每次获取缓存时都检查过期时间,在高并发场景下可能会有性能问题。
- 优化方向:
- 定时器合并:可以考虑使用一个统一的定时器,定期检查所有缓存项的过期时间,而不是为每个缓存项创建单独的定时器。
- 懒删除与定期清理:在获取缓存时不立即删除过期数据,而是标记为过期,然后通过一个后台任务定期清理过期数据,减少高并发场景下的性能开销。