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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| class CacheManager { constructor(redis, localCache) { this.redis = redis; this.localCache = localCache; this.bloomFilter = null; }
async get(key, queryDB, options = {}) { const { useBloom = false, useLock = false, useLocal = false, expireSeconds = 3600, nullExpireSeconds = 60 } = options;
if (useBloom && this.bloomFilter) { if (!this.bloomFilter.has(key)) { return null; } }
if (useLocal && this.localCache) { const localData = this.localCache.get(key); if (localData !== undefined) { return localData; } }
const cached = await this.redis.get(key); if (cached !== null) { if (cached === '__NULL__') { return null; } const data = JSON.parse(cached); if (useLocal) { this.localCache.set(key, data, 60); } return data; }
let data; if (useLock) { data = await this.getWithLock(key, queryDB, expireSeconds); } else { data = await queryDB(); await this.set(key, data, expireSeconds, nullExpireSeconds); }
if (useLocal && data !== null) { this.localCache.set(key, data, 60); }
return data; }
async set(key, value, expireSeconds, nullExpireSeconds = 60) { if (value === null) { await this.redis.setex(key, nullExpireSeconds, '__NULL__'); } else { const randomOffset = Math.floor(Math.random() * 600); await this.redis.setex( key, expireSeconds + randomOffset, JSON.stringify(value) ); } }
async getWithLock(key, queryDB, expireSeconds) { const lockKey = `lock:${key}`;
const acquired = await this.redis.set(lockKey, '1', 'EX', 10, 'NX');
if (!acquired) { await sleep(100); const cached = await this.redis.get(key); if (cached && cached !== '__NULL__') { return JSON.parse(cached); } return this.getWithLock(key, queryDB, expireSeconds); }
try { const cached = await this.redis.get(key); if (cached && cached !== '__NULL__') { return JSON.parse(cached); }
const data = await queryDB(); await this.set(key, data, expireSeconds); return data; } finally { await this.redis.del(lockKey); } } }
const cacheManager = new CacheManager(redis, localCache);
const user = await cacheManager.get( `user:${userId}`, () => db.query('SELECT * FROM users WHERE id = ?', [userId]), { expireSeconds: 3600 } );
const product = await cacheManager.get( `product:${productId}`, () => db.query('SELECT * FROM products WHERE id = ?', [productId]), { useBloom: true, useLock: true, useLocal: true, expireSeconds: 7200 } );
|