广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Consistent hashing i
  • 487
分享到

Consistent hashing i

Consistenthashing 2023-01-31 01:01:23 487人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

I have implemented consistent hashing in python. The module is called hash_ring and you can get it right away. This post

I have implemented consistent hashing in python. The module is called hash_ring and you can get it right away. This post will explain the motivation behind the project and details. I think other languages such as Ruby can reuse my code since it's fairly simple :-)

To install the project, simply do:

sudo easy_install  hash_ring

Example of usage when mapping keys to memcached servers:

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')


The motivation behind hash_ring

Consistent hashing is really neat and can be used anywhere where you have a list of servers and you need to map some keys (objects) to these servers. An example is memcached or a distributed system.

A problem when you use memcached clients is that you map keys to servers in following way:

server=serverlist[hash(key)%len(serverlist)]

The major problem with this approach is that you'll invalidate all your caches when you add or remove memcache servers to the list - and this invalidation can be very expensive if you rely on caching.

This problem was solved 10 years aGo by David Karger et al and they have published following articles that explain the idea of consistent caching in greater details:

  • Consistent Hashing and Random Trees: Distributed Caching Protocols for Relieving Hot Spots on the World Wide WEB

  • Web Caching with Consistent Hashing

Another motivation is that I am currently looking into building a distributed hash map - and consistent hashing is essential in such a system. Here are a few widely used systems that use consistent hashing:

  • Amazon Dynamo

  • BitTorrent

How consistent hashing works

Consistent hashing is fairly simple (and genius way of distributing keys). It can be best explained by the idea that you have a ring that goes from 0 to some big number. Given a node A, you find a placement for A on the ring by running hash_function(A), the hash_function should generally mix the values well - good candidates for the hash function are MD5 or SHA1. Given a (key, value) pair you find the key's placement on the ring by running hash_function(key). A node holds all the keys that have a value lower than itself, but greater than the preceding node.

Tom White has written a great blog post about consistent hashing, take a look at it, it explains the idea in much greater detail.

Python implementation

I think my Python implementation is beatiful so I will share the full implementation. The code speaks for itself or something:

import md5
class HashRing(object):
    def __init__(self, nodes=None, replicas=3):
        """Manages a hash ring.
        `nodes` is a list of objects that have a proper __str__ representation.
        `replicas` indicates how many virtual points should be used pr. node,
        replicas are required to improve the distribution.
        """
        self.replicas = replicas
        self.ring = dict()
        self._sorted_keys = []
        if nodes:
            for node in nodes:
                self.add_node(node)
    def add_node(self, node):
        """Adds a `node` to the hash ring (including a number of replicas).
        """
        for i in xrange(0, self.replicas):
            key = self.gen_key('%s:%s' % (node, i))
            self.ring[key] = node
            self._sorted_keys.append(key)
        self._sorted_keys.sort()
    def remove_node(self, node):
        """Removes `node` from the hash ring and its replicas.
        """
        for i in xrange(0, self.replicas):
            key = self.gen_key('%s:%s' % (node, i))
            del self.ring[key]
            self._sorted_keys.remove(key)
    def get_node(self, string_key):
        """Given a string key a corresponding node in the hash ring is returned.
        If the hash ring is empty, `None` is returned.
        """
        return self.get_node_pos(string_key)[0]
    def get_node_pos(self, string_key):
        """Given a string key a corresponding node in the hash ring is returned
        along with it's position in the ring.
        If the hash ring is empty, (`None`, `None`) is returned.
        """
        if not self.ring:
            return None, None
        key = self.gen_key(string_key)
        nodes = self._sorted_keys
        for i in xrange(0, len(nodes)):
            node = nodes[i]
            if key <= node:
                return self.ring[node], i
        return self.ring[nodes[0]], 0
    def get_nodes(self, string_key):
        """Given a string key it returns the nodes as a generator that can hold the key.
        The generator is never ending and iterates through the ring
        starting at the correct position.
        """
        if not self.ring:
            yield None, None
        node, pos = self.get_node_pos(string_key)
        for key in self._sorted_keys[pos:]:
            yield self.ring[key]
        while True:
            for key in self._sorted_keys:
                yield self.ring[key]
    def gen_key(self, key):
        """Given a string key it returns a long value,
        this long value represents a place on the hash ring.
        md5 is currently used because it mixes well.
        """
        m = md5.new()
        m.update(key)
        return long(m.hexdigest(), 16)


--结束END--

本文标题: Consistent hashing i

本文链接: https://www.lsjlt.com/news/183482.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Consistent hashing i
    I have implemented consistent hashing in Python. The module is called hash_ring and you can get it right away. This post...
    99+
    2023-01-31
    Consistent hashing
  • 如何实现Consistent Hashing算法
    这篇文章给大家分享的是有关如何实现Consistent Hashing算法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。在做服务器负载均衡时候可供选择的负载均衡的算法有很多,包括: 轮循算法(Round Robi...
    99+
    2023-06-17
  • 怎么理解mysql特性semi consistent read
    这篇文章主要讲解了“怎么理解mysql特性semi consistent read”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么理解mysql特性sem...
    99+
    2022-10-19
  • java中i=i++和j=i++的区别小结
    i=i++;j=i++的区别 i=i++-----------在java中 这个语句的前后顺序应该是这样的(tmp=i;i++;tmp==i) java的编译器在遇到i++和i- -...
    99+
    2022-11-12
  • java中i++与++i的区别
    i++是先赋值,再运算,++i是先运算,再赋值。实例如下:package com.test; public class TestAdd { public static void main(String[] args) { ...
    99+
    2017-03-13
    java入门 java i++ ++i 区别
  • 技术分享 | Jump Consistent Hash 原理解析(上篇)
    之前爱可生开源社区公众号发表了dble 沿用 jumpstringhash,移除 Mycat 一致性 hash 原因解析, 阐述了跳跃法相对环割法的性能优势。很多读者表示对其中"跳跃法的原理"不是很理解,本文就来详细阐述一下。 一致性哈希...
    99+
    2021-01-24
    技术分享 | Jump Consistent Hash 原理解析(上篇)
  • for循环中 i++ 和 ++i 区别
    一、for循环中 i++的使用 for (int i = 0;i < 10;i++){ } 二、for循环中 ++i 的使用 for (int i = 0;i ...
    99+
    2023-09-12
    java c++ 开发语言 Powered by 金山文档
  • 详解Python中表达式i += x与i = i + x是否等价
    前言 最近看到一个题目,看似很简单,其实里面有很深的意义,题目是Python 表达式 i += x 与 i = i + x 等价吗?如果你的回答是yes,那么恭喜你正确了50%,为什么说只对了一半呢? 按照...
    99+
    2022-06-04
    表达式 详解 Python
  • C语言中i++和++i的区别
    本篇内容主要讲解“C语言中i++和++i的区别”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C语言中i++和++i的区别”吧!i++ :先引用后增加++i :先...
    99+
    2022-10-19
  • MySQL中的@i:=@i+1用法详解
    在MySQL中,@i:=@i+1是一个非常有用的表达式,用于在查询中生成一个递增的序列号。它可以帮助我们对结果进行编号,或者在需要连续的数字序列时提供便利。 我们先来了解一下MySQL中的用户变量。用户变量是一个用户定义的变量,其以@开头。...
    99+
    2023-09-09
    mysql 数据库 sql
  • Python:expected an i
    IndentationError:expected an indented block错误解决这个错误的意思是缺少缩进注意提示你的代码内行,可能缩进出现问题。解决方法:在该缩进的地方加Tab或者空格(但不能混用)...
    99+
    2023-01-31
    Python expected
  • python2.7 MySQLdb i
    CREATE TABLE `a` (  `id` int(15) NOT NULL AUTO_INCREMENT,  `ip` varchar(20) NOT NULL,  `apply` varchar(20) NOT...
    99+
    2023-01-31
    MySQLdb
  • C语言i++和++i示例代码分析
    这篇文章主要讲解了“C语言i++和++i示例代码分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C语言i++和++i示例代码分析”吧!一看就懂的i++和++i详解前言我相信很多朋友可能之前...
    99+
    2023-07-05
  • java中的表达式i++和++i的区别
    区别:i++先赋值再自增;++i先自增再赋值。相关视频教程推荐:java视频教程例如: int i=0; System.out.println(i++); System.out.println(...
    99+
    2017-08-06
    java i++ ++i 区别
  • 浅谈JVM 底层解析 i++和 ++i 区别
    目录一、前言二、代码实现三、字节码指令四、字节码解析1. 第一类问题2. 第二类问题3. 第三类问题4. 第四类问题一、前言 如果只用普通的知识解释i++和++i的话 i++ 先将...
    99+
    2022-11-12
  • 如何通过PHP8的Consistent Type Errors提高代码健壮性?
    如何通过PHP8的Consistent Type Errors提高代码健壮性?摘要:PHP8引入了一种新的功能,称为Consistent Type Errors,它能够在编译时检测和显示类型错误。本文将介绍如何使用Consistent Ty...
    99+
    2023-10-22
    PHP 代码健壮性 Consistent Type Errors
  • ORA-10576: Give up restoring recovered datafiles to consistent state: some error occurred ORACLE 报错
    文档解释 ORA-10576: Give up restoring recovered datafiles to consistent state: some error occurred Cause: See alert file or ...
    99+
    2023-11-05
    报错 故障 restoring
  • python 字典i
    字典     字典类似于你通过联系人名称查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。     键值对在字典中以这样的方式标记:d...
    99+
    2023-01-31
    字典 python
  • C语言中的i++和++i有什么区别
    这篇文章主要讲解了“C语言中的i++和++i有什么区别”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C语言中的i++和++i有什么区别”吧!(1)如果只是看i++和++i,这两个是等价的,都...
    99+
    2023-06-03
  • c语言中i++和++i的区别是什么
    这篇文章主要讲解了“c语言中i++和++i的区别是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“c语言中i++和++i的区别是什么”吧!我们先用 while 语句写一下 i++:for(...
    99+
    2023-06-27
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作