flnxi-Wu/lib/cache.ts
WuYongJie f646b71813
Some checks failed
CI Check / check (push) Has been cancelled
chore: 初始化本地仓库并同步最近改动
2025-11-18 17:50:16 +08:00

106 lines
2.1 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 简单的内存缓存实现
* 适用于单实例部署,限制缓存大小和TTL
*
* 性能优化:减少数据库查询,提升响应速度
*/
interface CacheItem<T> {
data: T
expires: number
}
class SimpleCache {
private cache = new Map<string, CacheItem<any>>()
private maxSize = 1000 // 最大缓存项数
private defaultTTL = 60000 // 默认TTL:1分钟
/**
* 获取缓存
* @param key 缓存键
* @returns 缓存数据,如果过期或不存在则返回null
*/
get<T>(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<T>(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 }