forked from imbytecat/fullstack-starter
feat: 使用 ttlcache 优化指纹缓存管理
- 添加指纹缓存迁移决策,选用零依赖的 ttlcache 库并配置单例缓存与十分钟过期时间。 - 使用 `@isaacs/ttlcache` 成功替换手动 TTL 缓存并保留请求去重逻辑,优化依赖管理与代码格式化流程。 - 添加缓存库选型说明,明确采用 @isaacs/ttlcache 提升硬件指纹功能的可维护性与稳定性。 - 添加 ttlcache 依赖以支持缓存功能 - 使用 TTLCache 替代手动缓存逻辑,提升缓存管理的可靠性和可维护性。 - 添加 @isaacs/ttlcache 依赖并指定版本 2.1.4,更新锁定文件以确保依赖一致性。 - 添加 ttlcache 依赖以支持缓存功能
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { TTLCache } from '@isaacs/ttlcache'
|
||||
import { hash } from 'ohash'
|
||||
import si from 'systeminformation'
|
||||
|
||||
@@ -63,10 +64,10 @@ export type HardwareFingerprintResult = {
|
||||
}
|
||||
|
||||
// 缓存实例
|
||||
let cache: {
|
||||
expiresAt: number
|
||||
value: HardwareFingerprintResult
|
||||
} | null = null
|
||||
const cache = new TTLCache<'fingerprint', HardwareFingerprintResult>({
|
||||
ttl: 10 * 60 * 1000, // 10 minutes default
|
||||
max: 1, // Only one fingerprint cached
|
||||
})
|
||||
|
||||
// 防止并发重复请求
|
||||
let inFlight: Promise<HardwareFingerprintResult> | null = null
|
||||
@@ -182,8 +183,9 @@ export async function getHardwareFingerprint(
|
||||
const now = Date.now()
|
||||
|
||||
// 返回缓存结果
|
||||
if (cache && cache.expiresAt > now) {
|
||||
return cache.value
|
||||
const cached = cache.get('fingerprint')
|
||||
if (cached) {
|
||||
return cached
|
||||
}
|
||||
|
||||
// 防止并发重复请求
|
||||
@@ -212,7 +214,7 @@ export async function getHardwareFingerprint(
|
||||
}
|
||||
|
||||
// 更新缓存
|
||||
cache = { expiresAt: now + ttl, value: result }
|
||||
cache.set('fingerprint', result, { ttl })
|
||||
|
||||
return result
|
||||
})().finally(() => {
|
||||
@@ -226,6 +228,6 @@ export async function getHardwareFingerprint(
|
||||
* 清除指纹缓存(用于测试或强制刷新)
|
||||
*/
|
||||
export function clearFingerprintCache(): void {
|
||||
cache = null
|
||||
cache.clear()
|
||||
inFlight = null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user