python-memcached是否支持一致的哈希和&二进制协议?

时间:2010-04-11 09:45:28

标签: python django memcached python-memcached consistent-hashing

Python-memcached是官方支持的Django memcached驱动程序。

是否支持

  1. 一致性散列
  2. 二进制协议
  3. 如果是,请问如何在Django中使用这些功能?我找不到任何文件。

6 个答案:

答案 0 :(得分:2)

查看python-memcached v1.45上的_get_server方法,它似乎不使用一致哈希,而是一个简单的hash % len(buckets)

对于二进制协议也是如此,就我在源代码中看到的而言,python-memcache只使用文本命令。

答案 1 :(得分:1)

您可以使用此功能:http://amix.dk/blog/post/19370

它封装了python-memcache的Client类,因此使用一致的散列来分发密钥。

编辑 - 我正在挖掘python-memcached 1.4.5源代码,看起来它实际上可能支持一致的散列。 相关代码:

from binascii import crc32   # zlib version is not cross-platform
def cmemcache_hash(key):
    return((((crc32(key) & 0xffffffff) >> 16) & 0x7fff) or 1)
serverHashFunction = cmemcache_hash

-- SNIP --

def _get_server(self, key):
    if isinstance(key, tuple):
        serverhash, key = key
    else:
        serverhash = serverHashFunction(key)

    for i in range(Client._SERVER_RETRIES):
        server = self.buckets[serverhash % len(self.buckets)]
        if server.connect():
            #print "(using server %s)" % server,
            return server, key
        serverhash = serverHashFunction(str(serverhash) + str(i))
    return None, None

基于此代码,看起来它确实实现了算法,除非cmemcache_hash不是有意义的名称且不是真正的算法。 (现在已退休的cmemcache执行一致哈希)

但我认为OP指的是更具“弹性”的一致性散列,例如libketama。我不认为那里的解决方案有所下降,看起来你需要卷起袖子编译/安装一个更高级的memcached lib,如pylibmc,并编写一个使用它的自定义Django后端而不是python-memcached。

无论如何,在任何一种情况下,当您向池中添加/删除存储桶时,都会发生一些键的重新映射(即使使用libketama,只比其他算法少)

答案 2 :(得分:1)

请检查此示例python实现的一致哈希。

实施主体:想象一个连续的圈子,其中有许多复制的服务器点。当我们添加新服务器时,总数的1 / n   缓存键将丢失

 '''consistent_hashing.py is a simple demonstration of consistent
hashing.'''

import bisect
import hashlib

class ConsistentHash:
  '''

  To imagine it is like a continnum circle with a number of replicated
  server points spread across it. When we add a new server, 1/n of the total
  cache keys will be lost. 

  consistentHash(n,r) creates a consistent hash object for a 
  cluster of size n, using r replicas. 

  It has three attributes. num_machines and num_replics are
  self-explanatory.  hash_tuples is a list of tuples (j,k,hash), 
  where j ranges over machine numbers (0...n-1), k ranges over 
  replicas (0...r-1), and hash is the corresponding hash value, 
  in the range [0,1).  The tuples are sorted by increasing hash 
  value.

  The class has a single instance method, get_machine(key), which
  returns the number of the machine to which key should be 
  mapped.'''
  def __init__(self,replicas=1):
      self.num_replicas = replicas

  def setup_servers(self,servers=None):
    hash_tuples = [(index,k,my_hash(str(index)+"_"+str(k))) \
               for index,server in enumerate(servers)
               for k in range(int(self.num_replicas) * int(server.weight)) ]
    self.hash_tuples=self.sort(hash_tuples);

  def sort(self,hash_tuples):
    '''Sort the hash tuples based on just the hash values   '''
    hash_tuples.sort(lambda x,y: cmp(x[2],y[2]))
    return hash_tuples

  def add_machine(self,server,siz):
    '''This mathod adds a new machine. Then it updates the server hash
     in the continuum circle '''
    newPoints=[(siz,k,my_hash(str(siz)+"_"+str(k))) \
                   for k in range(self.num_replicas*server.weight)]
    self.hash_tuples.extend(newPoints)
    self.hash_tuples=self.sort(self.hash_tuples);



  def get_machine(self,key):
    '''Returns the number of the machine which key gets sent to.'''
    h = my_hash(key)
    # edge case where we cycle past hash value of 1 and back to 0.
    if h > self.hash_tuples[-1][2]: return self.hash_tuples[0][0]
    hash_values = map(lambda x: x[2],self.hash_tuples)
    index = bisect.bisect_left(hash_values,h)
    return self.hash_tuples[index][0]

def my_hash(key):
  '''my_hash(key) returns a hash in the range [0,1).'''
  return (int(hashlib.md5(key).hexdigest(),16) % 1000000)/1000000.0

答案 3 :(得分:0)

现在vbucket即将解决一致哈希问题,对缓存未命中影响最小。

答案 4 :(得分:0)

如果您想要django的即插即用解决方案,请使用django-memcached-hashringhttps://github.com/jezdez/django-memcached-hashring

它是django.core.cache.backends.memcached.MemcachedCachehash_ring库附近的适配器。

答案 5 :(得分:0)

我使用了Consistent散列算法。丢失的密钥是密钥总数的1 / n。这意味着成功的密钥提取将是大约85%的6/7 * 100。 here