1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| class UserCache { constructor() { this.cache = new Map(); this.maxSize = 10000; this.ttl = 5 * 60 * 1000; }
async get(userId) { const key = `user:${userId}`; const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.ttl) { return cached.data; }
const data = await this.fetchFromDB(userId);
this.set(key, data);
return data; }
set(key, data) { if (this.cache.size >= this.maxSize) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); }
this.cache.set(key, { data: data, timestamp: Date.now() }); }
async fetchFromDB(userId) { return await db.users.find( { id: userId }, { projection: { id: 1, name: 1, level: 1, region: 1 } } ); }
async getWithNullCache(userId) { const key = `user:${userId}`; const cached = this.cache.get(key);
if (cached) { if (cached.isNull) return null; if (Date.now() - cached.timestamp < this.ttl) { return cached.data; } }
const data = await this.fetchFromDB(userId);
if (data) { this.set(key, data); } else { this.cache.set(key, { isNull: true, timestamp: Date.now() }); }
return data; } }
class RedisUserCache { async get(userId) { const key = `user:${userId}`; let data = await redis.get(key);
if (data) { return JSON.parse(data); }
const lockKey = `lock:${key}`; const lock = await redis.set(lockKey, '1', 'NX', 'EX', 10);
if (lock) { try { data = await this.fetchFromDB(userId); if (data) { await redis.setex(key, 300, JSON.stringify(data)); } else { await redis.setex(key, 60, 'null'); } } finally { await redis.del(lockKey); } } else { await new Promise(resolve => setTimeout(resolve, 100)); return this.get(userId); }
return data; } }
|