一致性hash


#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函数设置的好 虚拟节点设置的很均匀的话  玩家在服务器上分布的就很均匀。。。。。。。

这只是一个实践罢了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值