[docs]classKeyRouter:def__init__(self,nodes:set[SingleMemcachedInstanceEndpoint]|None=None,hasher:Callable[[str],int]|None=None,)->None:""" Rendezvous Hashing implementation to route keys to memcached nodes. :param nodes: set of memcached nodes that are candidates :param hasher: function to use to hash a key to a node. If not provided, a default implementation using :func:`hashlib.md5` from the standard library will be used. """self._hasher=hasherormd5_hasherself.nodes:set[SingleMemcachedInstanceEndpoint]=nodesorset()
[docs]defadd_node(self,node:SingleMemcachedInstanceEndpoint)->None:""" Add a node to the set of candidate nodes """self.nodes.add(node)
[docs]defremove_node(self,node:SingleMemcachedInstanceEndpoint)->None:""" Remove a node from the set of candidate nodes """self.nodes.discard(node)
[docs]defget_node(self,key:str)->SingleMemcachedInstanceEndpoint:""" Get the node associated with ``key`` """ifnotself.nodes:raiseNoAvailableNodes()returnmax(self.nodes,key=lambdanode:self._hasher(f"{node}:{key}"))