您好,登錄后才能下訂單哦!
量少的場景, 一致性hash不均勻的問題很難解決,加500個虛擬節點也不是很管用
算法很簡單,自己用函數寫了一下,僅供參考:
import hashlib
server_ip_list = ["192.168.1.10", "192.168.2.20", "192.168.3.30","192.168.4.40"]
client_ip_list = ["113.88.97.173", "106.11.154.33", "207.46.13.149","42.156.137.120", "203.208.60.0", "119.39.47.182", "171.34.179.4", "111.175.58.52", "124.235.138.199","175.184.166.184","111.175.58.52", "124.235.18.119","175.144.163.124","175.14.166.114","111.175.8.152", "124.23.18.113","175.144.13.116"]
def get_md5(data):
m = hashlib.md5()
m.update(data.encode('utf-8'))
return m.hexdigest()
def get_ip():
virtual_nodes = 500
node_dict = {}
# 遍歷服務器ip,生成對應的虛擬結點
for serverip in server_ip_list:
for i in range(virtual_nodes):
# serverip加上一些動態參數生成md5值
hash_key = get_md5(str('{0}VN{1}'.format(serverip,i)))
node_dict[hash_key]=serverip
# 將node_dict字典按key排序生成列表
sorted_key_list = sorted(node_dict)
# 將node_dict字典按key排序
node_dict = sorted(node_dict.items(),key=lambda d:d[0],reverse=False)
#print(node_dict)
#print(sorted_key_list)
for clientip in client_ip_list:
selected_key_list = []
# clientip生成md5值
hc = get_md5(str(clientip))
#print(hc)
switch = 0
for key in sorted_key_list:
#print(key)
# clientip和sorted_key_list中的md5值做比較,clientip的md5值小于等于sorted_key_list中的md5值,switch=1
if hc <= key:
selected_key_list.append(key)
switch=1
if switch == 0:
firstkey = sorted_key_list[0]
else:
firstkey = selected_key_list[0]
#print(firstkey)
#print(selected_key_list)
print("{0}請求的服務器ip為:{1}".format(clientip,dict(node_dict)[firstkey]))
# for i in range(2):
get_ip()
執行結果:
113.88.97.173請求的服務器ip為:192.168.2.20
106.11.154.33請求的服務器ip為:192.168.4.40
207.46.13.149請求的服務器ip為:192.168.3.30
42.156.137.120請求的服務器ip為:192.168.3.30
203.208.60.0請求的服務器ip為:192.168.3.30
119.39.47.182請求的服務器ip為:192.168.3.30
171.34.179.4請求的服務器ip為:192.168.4.40
111.175.58.52請求的服務器ip為:192.168.1.10
124.235.138.199請求的服務器ip為:192.168.3.30
175.184.166.184請求的服務器ip為:192.168.3.30
111.175.58.52請求的服務器ip為:192.168.1.10
124.235.18.119請求的服務器ip為:192.168.2.20
175.144.163.124請求的服務器ip為:192.168.2.20
175.14.166.114請求的服務器ip為:192.168.4.40
111.175.8.152請求的服務器ip為:192.168.2.20
124.23.18.113請求的服務器ip為:192.168.1.10
175.144.13.116請求的服務器ip為:192.168.4.40
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。