# 三分钟看懂一致性哈希算法

node a: 0,3,6,9

node b: 1,4,7

node c: 2,5,8

node a:0,4,8

node b:1,5,9

node c: 2,6

node d: 3,7

0：192

1：196

2：200

3：204

4：208

5：212

6：216

7：220

8：224

9：228

node a: 203

node g: 209

node z: 228

node a: 0,1,2

node g: 3,4

node z: 5,6,7,8,9

node n: 216

node a: 0,1,2

node g: 3,4

node n: 5,6

node z: 7,8,9

import md5
class HashRing(object):
def __init__(self, nodes=None, replicas=3):
"""Manages a hash ring.
nodes is a list of objects that have a proper __str__ representation.
replicas indicates how many virtual points should be used pr. node,
replicas are required to improve the distribution.
"""
self.replicas = replicas
self.ring = dict()
self._sorted_keys = []
if nodes:
for node in nodes:
"""Adds a node to the hash ring (including a number of replicas).
"""
for i in xrange(0, self.replicas):
key = self.gen_key('%s:%s' % (node, i))
print "node %s-%s key is %ld" % (node, i, key)
self.ring[key] = node
self._sorted_keys.append(key)
self._sorted_keys.sort()
def remove_node(self, node):
"""Removes node from the hash ring and its replicas.
"""
for i in xrange(0, self.replicas):
key = self.gen_key('%s:%s' % (node, i))
del self.ring[key]
self._sorted_keys.remove(key)
def get_node(self, string_key):
"""Given a string key a corresponding node in the hash ring is returned.
If the hash ring is empty, None is returned.
"""
return self.get_node_pos(string_key)[0]
def get_node_pos(self, string_key):
"""Given a string key a corresponding node in the hash ring is returned
along with it's position in the ring.
If the hash ring is empty, (None, None) is returned.
"""
if not self.ring:
return None, None
key = self.gen_key(string_key)
nodes = self._sorted_keys
for i in xrange(0, len(nodes)):
node = nodes[i]
if key <= node:
print "string_key %s key %ld" % (string_key, key)
print "get node %s-%d " % (self.ring[node], i)
return self.ring[node], i
return self.ring[nodes[0]], 0
def print_ring(self):
if not self.ring:
return None, None
nodes = self._sorted_keys
for i in xrange(0, len(nodes)):
node = nodes[i]
print "ring slot %d is node %s, hash vale is %s" % (i, self.ring[node], node)
def get_nodes(self, string_key):
"""Given a string key it returns the nodes as a generator that can hold the key.
The generator is never ending and iterates through the ring
starting at the correct position.
"""
if not self.ring:
yield None, None
node, pos = self.get_node_pos(string_key)
for key in self._sorted_keys[pos:]:
yield self.ring[key]
while True:
for key in self._sorted_keys:
yield self.ring[key]
def gen_key(self, key):
"""Given a string key it returns a long value,
this long value represents a place on the hash ring.
md5 is currently used because it mixes well.
"""
m = md5.new()
m.update(key)
return long(m.hexdigest(), 16)
"""
hash = 0
for i in xrange(0, len(key)):
hash += ord(key[i])
return hash
"""

memcache_servers = ['a',
'g',
'z']
ring = HashRing(memcache_servers,1)
ring.print_ring()
server = ring.get_node('0000')
server = ring.get_node('1111')
server = ring.get_node('2222')
server = ring.get_node('3333')
server = ring.get_node('4444')
server = ring.get_node('5555')
server = ring.get_node('6666')
server = ring.get_node('7777')
server = ring.get_node('8888')
server = ring.get_node('9999')

print '----------------------------------------------------------'

memcache_servers = ['a',
'g',
'n',
'z']
ring = HashRing(memcache_servers,1)
ring.print_ring()
server = ring.get_node('0000')
server = ring.get_node('1111')
server = ring.get_node('2222')
server = ring.get_node('3333')
server = ring.get_node('4444')
server = ring.get_node('5555')
server = ring.get_node('6666')
server = ring.get_node('7777')
server = ring.get_node('8888')
server = ring.get_node('9999')


• 20
点赞
• 6
收藏
• 打赏
• 7
评论
11-18 109
12-03 85
03-08 1万+
05-15 295
10-17 2万+
09-26 2269
10-28 1449
07-13 137
09-06 2906
02-29 1687
10-24 2531

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

gerryke

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。