#coding:utf-8
'''
create on 2020-11-24
@author:sandy
'''
import crc16pure
class Node(object):
def __init__(self,ip,name,virtual):
self.ip = ip
self.name = name
self.virtual = virtual
def getIp(self):
return self.ip
def getName(self):
return self.name
def getVirtual(self):
return self.virtual
class ConsistentHash(object):
def __init__(self,number):
self.numberOfReplicas = number
self.circle = {}
def add(self,node):
for i in range(self.numberOfReplicas):
hashcode = crc16pure.crc16xmodem(node.getVirtual() + str(i))
self.circle[hashcode] = node
def remove(self,node):
for i in range(self.numberOfReplicas):
hashcode = crc16pure.crc16xmodem(node.getVirtual() + str(i))
self.circle.pop(hashcode)
pass
def get(self,key):
hashcode = crc16pure.crc16xmodem(key)
hashcodes = self.circle.keys()
hashcodes.sort()
if hashcode not in hashcodes:
index = 0
if hashcode < hashcodes[0] or hashcode > hashcodes[-1]:
hashcode = hashcodes[0]
else:
i = 0
j = len(hashcodes) - 1
mid = int((i + j) / 2)
while True:
if hashcode < hashcodes[mid]:
j = mid
else:
i = mid
mid = int((i + j) / 2)
if mid == i:
index = j
break
hashcode = hashcodes[index]
return self.circle.get(hashcode)
if __name__ == '__main__':
con = ConsistentHash(1000)
for i in range(4):
node = Node("192.168.0.%s" % i,"center%s" % i,"real_node%s" % i)
con.add(node)
print(node)
print("##################################")
tmp = {}
startuid = 1000
for i in range(5000):
node = con.get(str(startuid + i))
oldcount = tmp.get(node,0)
tmp[node] = oldcount + 1
pass
print(tmp)
4台真实的 每个附属1000个虚拟节点,5000人的分布情况 总体还算均匀吧,如果hash函数设置的好 虚拟节点设置的很均匀的话 玩家在服务器上分布的就很均匀。。。。。。。
这只是一个实践罢了