首先安裝python的一致性hash實現庫hash_ringnode
pip install hash_ring
而後使用hash_ringpython
from hash_ring import HashRing memcache_servers = ['192.168.0.246:11212', '192.168.0.247:11212', '192.168.0.249:11212'] ring = HashRing(memcache_servers) server = ring.get_node('my_key')
一致性hash能夠用在服務器的負載均衡下,用來多服務器或多數據庫提供服務時,能夠將請求平均分發給每一個servershell
能夠提供第二個參數用來設置每一個服務的權重數據庫
from hash_ring import HashRing memcache_servers = ['192.168.0.246:11212', '192.168.0.247:11212', '192.168.0.249:11212'] servers_weights = {'192.168.0.246:11212':1, '192.168.0.247:11212':2, '192.168.0.249:11212':3} ring = HashRing(memcache_servers, weights=servers_weights) server = ring.get_node('my_key')