环与虚拟节点(简化示例)
环与虚拟节点(简化示例)
import bisect, hashlib
class Ring:
def __init__(self, nodes, vnodes=100):
self.points = []
for n in nodes:
for i in range(vnodes):
h = hashlib.md5(("%s#%d" % (n, i)).encode()).hexdigest()
self.points.append((int(h, 16), n))
self.points.sort()
def node_for(self, key):
h = int(hashlib.md5(key.encode()).hexdigest(), 16)
i = bisect.bisect(self.points, (h,)) % len(self.points)
return self.points[i][1]
Redis Cluster 固定 16384 个槽,key 经 CRC16 取模定位槽位;用 hash tag(形如 user:{42}:name)可把相关 key 固定到同一个槽,便于批量操作。