优化用户管理

This commit is contained in:
mtvpls
2025-12-24 20:49:00 +08:00
parent 558ba174fe
commit c425db7e0e
4 changed files with 184 additions and 32 deletions
+59 -1
View File
@@ -55,6 +55,51 @@ class UserInfoCache {
}
}
// 站长存在状态缓存
class OwnerExistenceCache {
private cache: Map<string, { exists: boolean; cachedAt: number }> = new Map();
private readonly TTL = 10 * 60 * 1000; // 10分钟过期
get(ownerUsername: string): boolean | null {
const cached = this.cache.get(ownerUsername);
if (!cached) return null;
// 检查是否过期
if (Date.now() - cached.cachedAt > this.TTL) {
this.cache.delete(ownerUsername);
return null;
}
return cached.exists;
}
set(ownerUsername: string, exists: boolean): void {
this.cache.set(ownerUsername, {
exists,
cachedAt: Date.now(),
});
}
delete(ownerUsername: string): void {
this.cache.delete(ownerUsername);
}
clear(): void {
this.cache.clear();
}
// 清理过期的缓存
cleanup(): void {
const now = Date.now();
const entries = Array.from(this.cache.entries());
for (const [username, cached] of entries) {
if (now - cached.cachedAt > this.TTL) {
this.cache.delete(username);
}
}
}
}
// 全局单例
const globalKey = Symbol.for('__MOONTV_USER_INFO_CACHE__');
let userInfoCache: UserInfoCache | undefined = (global as any)[globalKey];
@@ -69,4 +114,17 @@ if (!userInfoCache) {
}, 60 * 1000);
}
export { userInfoCache };
const ownerExistenceGlobalKey = Symbol.for('__MOONTV_OWNER_EXISTENCE_CACHE__');
let ownerExistenceCache: OwnerExistenceCache | undefined = (global as any)[ownerExistenceGlobalKey];
if (!ownerExistenceCache) {
ownerExistenceCache = new OwnerExistenceCache();
(global as any)[ownerExistenceGlobalKey] = ownerExistenceCache;
// 每分钟清理一次过期缓存
setInterval(() => {
ownerExistenceCache?.cleanup();
}, 60 * 1000);
}
export { userInfoCache, ownerExistenceCache };