// Redis原子锁+Lua脚本 constacquireLock=async(key, ttl=5)=>{const result =await redis.set(key,1,'NX','EX', ttl);return result ==='OK';};constgetData=async(key)=>{let data =await redis.get(key);if(!data){if(awaitacquireLock(`${key}_lock`)){ data =await db.query(key);await redis.set(key, data,'EX',300);await redis.del(`${key}_lock`);}else{awaitnewPromise(r=>setTimeout(r,100));returngetData(key);}}return data;};
一致性哈希算法实现
classConsistentHash{constructor(nodes, replicas=200){this.ring =newMap(); nodes.forEach(node=>{for(let i =0; i < replicas; i++){const hash = crypto.createHash('md5').update(node + i).digest('hex');this.ring.set(hash, node);}});this.keys = Array.from(this.ring.keys()).sort();}getNode(key){const hash = crypto.createHash('md5').update(key).digest('hex');const idx =this.keys.findIndex(k=> k > hash);returnthis.ring.get(this.keys[idx %this.keys.length]);}}