Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 600|回复: 0

[默认分类] _00013 一致性哈希算法 Consistent Hashing 探讨以及相应的新问题出现解决

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-5-16 18:14:29 | 显示全部楼层 |阅读模式
    博文作者:妳那伊抹微笑
    博客地址:http://blog.csdn.net/u012185296
    个性签名:世界上最遥远的距离不是天涯,也不是海角,而是我站在妳的面前,妳却感觉不到我的存在
    技术方向:Flume+Kafka+storm+Redis/Hbase+hadoop+Hive+Mahout+Spark ... 云计算技术
    转载声明:可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明,谢谢合作!
    qq交流群:214293307  (期待与你一起学习,共同进步)


    一、业务场景假如我们现在有12台Redis服务器(其它的什么东西也行),有很多User(用户)的数据数据从前端过来,然后往12台redis服务器上存储,在存储中就会出现一个问题,12台服务器,有可能其中几台Redis服务器上(简称集群A)存了很多的数据,然后另外几台Redis服务器(简称集群B)上存的数据很少,这样的话那 A 上的读写压力就会很大(当然,这个要看你的数据量的大小了,如果你数据量很小的话,基本无压力了,但是数据量很大,那就 、、、),对于这样的问题,我们通常的解决办法是什么呢 ?一般通常会想到的就是哈希取余了吧!也就是 Hash(userid)% N (N=12),这样的话也能适当的减小很多压力了,但是这样的话又会产生一些新的问题,增加节点跟减少节点 :1、减少节点:假如有一台Redis服务器挂掉了,那么是否这样 Hash(userid)% N (N=12) 哈希取余到该Redis的数据会全部丢失呢 ?如果不要该节点,那么只剩下11台Redis服务器了,原来的映射关系 Hash(userid)% N (N=12) 变成了 Hash(userid)% (N-1) (N=12),重点是数据丢失如何找回 ?2、增加节点:假如有一天想增加Redis服务器了,这时候麻烦来了,这时候需要将原来的映射关系 Hash(userid)% N (N=12) 变成 Hash(userid)% (N+1) (N=12) 了,跟 减少节点一样,这岂不是以前所有的映射全部失效了 ?这不是坑爹么!!!数据混乱,后台可能瞬间垮掉,那样的代价很大 、、、3、硬件越来越便宜了,公司越来越大了,然后服务器越来越多了:哈希取余 Hash(userid)% N (N=12) 就也完全不能满足需求了,不能修改映射关系,修改之后灰常麻烦 。这时候该怎么办呢 ?有什么办法可以改变这个状况呢,当然就是一致性哈希 Consistent Hashing了 ......自己懒得写原理了,下面引用了 http://blog.csdn.net/sparkliang/article/details/5279393,详细介绍了一致性哈希,灰常好 、、、二、 hash 算法和单调性   Hash 算法的一个衡量指标是单调性( Monotonicity ),定义如下:  单调性是指如果已经有一些内容通过哈希分派到了相应的缓冲中,又有新的缓冲加入到系统中。哈希的结果应能够保证原有已分配的内容可以被映射到新的缓冲中去,而不会被映射到旧的缓冲集合中的其他缓冲区。容易看到,上面的简单 hash 算法 hash(object)%N 难以满足单调性要求。
    三、Consistent hashing 算法的原理Consistent Hashing 是一种 hash 算法,简单的说,在移除 / 添加一个 cache 时,它能够尽可能小的改变已存在 key 映射关系,尽可能的满足单调性的要求。下面就来按照 5 个步骤简单讲讲 consistent hashing 算法的基本原理。
    四、环形hash 空间考虑通常的 hash 算法都是将 value 映射到一个 32 为的 key 值,也即是 0~2^32-1 次方的数值空间;我们可以将这个空间想象成一个首( 0 )尾( 2^32-1 )相接的圆环,如下面图 1 所示的那样。图 1 环形 hash 空间五、把对象映射到hash 空间接下来考虑 4 个对象 object1~object4 ,通过 hash 函数计算出的 hash 值 key 在环上的分布如图 2 所示。hash(object1) = key1;… …hash(object4) = key4;图 2 4 个对象的 key 值分布六、 把cache 映射到hash 空间Consistent Hashing 的基本思想就是将对象和 cache 都映射到同一个 hash 数值空间中,并且使用相同的 hash算法。假设当前有 A,B 和 C 共 3 台 cache ,那么其映射结果将如图 3 所示,他们在 hash 空间中,以对应的 hash 值排列。hash(cache A) = key A;… …hash(cache C) = key C;图 3 cache 和对象的 key 值分布 说到这里,顺便提一下 cache 的 hash 计算,一般的方法可以使用 cache 机器的 IP 地址或者机器名作为 hash输入。
    七、把对象映射到cache现在 cache 和对象都已经通过同一个 hash 算法映射到 hash 数值空间中了,接下来要考虑的就是如何将对象映射到 cache 上面了。在这个环形空间中,如果沿着顺时针方向从对象的 key 值出发,直到遇见一个 cache ,那么就将该对象存储在这个 cache 上,因为对象和 cache 的 hash 值是固定的,因此这个 cache 必然是唯一和确定的。这样不就找到了对象和 cache 的映射方法了吗?!依然继续上面的例子(参见图 3 ),那么根据上面的方法,对象 object1 将被存储到 cache A 上; object2 和object3 对应到 cache C ; object4 对应到 cache B ;
    八、 考察cache 的变动前面讲过,通过 hash 然后求余的方法带来的最大问题就在于不能满足单调性,当 cache 有所变动时, cache会失效,进而对后台服务器造成巨大的冲击,现在就来分析分析 consistent hashing 算法。
    九、移除 cache考虑假设 cache B 挂掉了,根据上面讲到的映射方法,这时受影响的将仅是那些沿 cache B 顺时针遍历直到下一个 cache ( cache C )之间的对象,也即是本来映射到 cache B 上的那些对象。因此这里仅需要变动对象 object4 ,将其重新映射到 cache C 上即可;参见图 4 。图 4 Cache B 被移除后的 cache 映射十、添加 cache再考虑添加一台新的 cache D 的情况,假设在这个环形 hash 空间中, cache D 被映射在对象 object2 和object3 之间。这时受影响的将仅是那些沿 cache D 顺时针遍历直到下一个 cache ( cache B )之间的对象(它们是也本来映射到 cache C 上对象的一部分),将这些对象重新映射到 cache D 上即可。 因此这里仅需要变动对象 object2 ,将其重新映射到 cache D 上;参见图 5 。图 5 添加 cache D 后的映射关系十一、虚拟节点考量 Hash 算法的另一个指标是平衡性 (Balance) ,定义如下:平衡性   平衡性是指哈希的结果能够尽可能分布到所有的缓冲中去,这样可以使得所有的缓冲空间都得到利用。hash 算法并不是保证绝对的平衡,如果 cache 较少的话,对象并不能被均匀的映射到 cache 上,比如在上面的例子中,仅部署 cache A 和 cache C 的情况下,在 4 个对象中, cache A 仅存储了 object1 ,而 cache C 则存储了object2 、 object3 和 object4 ;分布是很不均衡的。为了解决这种情况, consistent hashing 引入了“虚拟节点”的概念,它可以如下定义:“虚拟节点”( virtual node )是实际节点在 hash 空间的复制品( replica ),一实际个节点对应了若干个“虚拟节点”,这个对应个数也成为“复制个数”,“虚拟节点”在 hash 空间中以 hash 值排列。仍以仅部署 cache A 和 cache C 的情况为例,在图 4 中我们已经看到, cache 分布并不均匀。现在我们引入虚拟节点,并设置“复制个数”为 2 ,这就意味着一共会存在 4 个“虚拟节点”, cache A1, cache A2 代表了cache A ; cache C1, cache C2 代表了 cache C ;假设一种比较理想的情况,参见图 6 。图 6 引入“虚拟节点”后的映射关系 此时,对象到“虚拟节点”的映射关系为:objec1->cache A2 ; objec2->cache A1 ; objec3->cache C1 ; objec4->cache C2 ;因此对象 object1 和 object2 都被映射到了 cache A 上,而 object3 和 object4 映射到了 cache C 上;平衡性有了很大提高。引入“虚拟节点”后,映射关系就从 { 对象 -> 节点 } 转换到了 { 对象 -> 虚拟节点 } 。查询物体所在 cache 时的映射关系如图 7 所示。图 7 查询对象所在 cache “虚拟节点”的 hash 计算可以采用对应节点的 IP 地址加数字后缀的方式。例如假设 cache A 的 IP 地址为202.168.14.241 。引入“虚拟节点”前,计算 cache A 的 hash 值:Hash(“202.168.14.241”);引入“虚拟节点”后,计算“虚拟节”点 cache A1 和 cache A2 的 hash 值:Hash(“202.168.14.241#1”);  // cache A1Hash(“202.168.14.241#2”);  // cache A2引用了这位大神的小结Consistent hashing 的基本原理就是这些,具体的分布性等理论分析应该是很复杂的,不过一般也用不到。http://weblogs.java.net/blog/2007/11/27/consistent-hashing 上面有一个 java 版本的例子,可以参考。http://blog.csdn.net/mayongzhan/archive/2009/06/25/4298834.aspx 转载了一个 PHP 版的实现代码。http://www.codeproject.com/KB/recipes/lib-conhash.aspx C语言版本
    先上代码吧,等下说一下一致性哈希中的一些问题1、未重构的代码
    1. import java.util.Collection;
    2. import java.util.SortedMap;
    3. import java.util.TreeMap;
    4. public class ConsistentHash<T> {
    5. private final HashFunction hashFunction;
    6. private final int numberOfReplicas;
    7. private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>();
    8. public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,
    9.      Collection<T> nodes) {
    10.    this.hashFunction = hashFunction;
    11.    this.numberOfReplicas = numberOfReplicas;
    12.    for (T node : nodes) {
    13.      add(node);
    14.    }
    15. }
    16. public void add(T node) {
    17.    for (int i = 0; i < numberOfReplicas; i++) {
    18.      circle.put(hashFunction.hash(node.toString() + i), node);
    19.    }
    20. }
    21. public void remove(T node) {
    22.    for (int i = 0; i < numberOfReplicas; i++) {
    23.      circle.remove(hashFunction.hash(node.toString() + i));
    24.    }
    25. }
    26. public T get(Object key) {
    27.    if (circle.isEmpty()) {
    28.      return null;
    29.    }
    30.    int hash = hashFunction.hash(key);
    31.    if (!circle.containsKey(hash)) {
    32.      SortedMap<Integer, T> tailMap = circle.tailMap(hash);
    33.      hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
    34.    }
    35.    return circle.get(hash);
    36. }
    37. }
    复制代码
    2、重构后的代码,将哈希算法跟虚拟节点的方法给抽取出来,模版方法设计模式2.1 AbstractConsistentHash
    1. package cn.yting.conhash;
    2. import java.util.Collection;
    3. import java.util.SortedMap;
    4. import java.util.TreeMap;
    5. /**
    6. * 将Hash算法跟虚拟节点的虚拟方式给抽出来,模版方法设计模式
    7. *
    8. * @Author 妳那伊抹微笑
    9. *
    10. */
    11. public abstract class AbstractConsistentHash {
    12. /**
    13. * 复制节点,增加每个节点的复制节点有利于负载均衡
    14. */
    15. protected int numberOfReplicas = 8;
    16. /**
    17. * 一致性哈希
    18. */
    19. protected SortedMap<Long, String> circle = new TreeMap<Long, String>();
    20. /**
    21. * 自定义一致性哈希算法
    22. */
    23. protected abstract long defineHash(String key);
    24. /**
    25. * 自定义circle key
    26. */
    27. protected abstract String defineCircleKey(String node, int i);
    28. public AbstractConsistentHash() {
    29. }
    30. public AbstractConsistentHash(int numberOfReplicas, Collection<String> nodes) {
    31. this.numberOfReplicas = numberOfReplicas;
    32. for (String node : nodes) {
    33. addNode(node);
    34. }
    35. }
    36. /**
    37. * 添加节点
    38. */
    39. public void addNode(String node) {
    40. for (int i = 0; i < this.numberOfReplicas; i++) {
    41. /*
    42. * 计算key的哈希算法
    43. */
    44. long key = defineHash(defineCircleKey(node, i));
    45. circle.put(key, node);
    46. }
    47. }
    48. /**
    49. * 删除节点
    50. */
    51. public void removeNode(String node) {
    52. for (int i = 0; i < this.numberOfReplicas; i++) {
    53. /*
    54. * 计算key的哈希算法
    55. */
    56. long key = defineHash(defineCircleKey(node, i));
    57. circle.remove(key);
    58. }
    59. }
    60. /**
    61. * 查找节点,取得顺时针方向上最近的一个虚拟节点对应的实际节点
    62. */
    63. public String getNode(String node) {
    64. if (circle.isEmpty()) {
    65. return null;
    66. }
    67. /*
    68. * 计算key的哈希算法
    69. */
    70. long key = defineHash(node);
    71. if (!circle.containsKey(key)) {
    72. SortedMap<Long, String> tailMap = circle.tailMap(key);
    73. key = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
    74. }
    75. return circle.get(key);
    76. }
    77. }
    复制代码
    2.2 hashCode 一致性哈希实现方式
    1. package cn.yting.conhash;
    2. import java.util.Set;
    3. /**
    4. * HashCode 一致性哈希,使用自带的hashCode计算hash值
    5. *
    6. * @Author 妳那伊抹微笑
    7. *
    8. */
    9. public class HashCodeConsistentHash extends AbstractConsistentHash {
    10. public HashCodeConsistentHash(int numberOfReplicas, Set<String> nodes) {
    11. super(numberOfReplicas, nodes);
    12. }
    13. @Override
    14. protected long defineHash(String key) {
    15. return key.hashCode();
    16. }
    17. @Override
    18. protected String defineCircleKey(String node, int i) {
    19. if(i > 99){
    20. return node + &quot;-&quot; + i;
    21. }else if(i > 9){
    22. return node + &quot;-0&quot; + i;
    23. }else{
    24. return node + &quot;-00&quot; + i;
    25. }
    26. }
    27. }
    复制代码
    2.3 CRC32 一致性哈希实现方式
    1. package cn.yting.conhash;
    2. import java.util.Set;
    3. import java.util.zip.CRC32;
    4. /**
    5. * HashCode 一致性哈希,使用CRC32算法计算hash值
    6. *
    7. * @Author 妳那伊抹微笑
    8. *
    9. */
    10. public class CRC32ConsistentHash extends AbstractConsistentHash {
    11. public CRC32ConsistentHash(int numberOfReplicas, Set<String> nodes) {
    12. super(numberOfReplicas, nodes);
    13. }
    14. @Override
    15. protected long defineHash(String key) {
    16. CRC32 hash = new CRC32();
    17. hash.update(key.getBytes());
    18. return (int)hash.getValue();
    19. }
    20. @Override
    21. protected String defineCircleKey(String node, int i) {
    22. return (node+i);
    23. }
    24. }
    复制代码
    2.4  MD5 一致性哈希 实现方式
    1. package cn.yting.conhash;
    2. import java.nio.charset.Charset;
    3. import java.security.MessageDigest;
    4. import java.util.Set;
    5. /**
    6. * HashCode 一致性哈希,使用自MD5算法计算hash值
    7. *
    8. * @Author 妳那伊抹微笑
    9. *
    10. */
    11. public class MD5ConsistentHash extends AbstractConsistentHash{
    12. public MD5ConsistentHash(int numberOfReplicas, Set<String> nodes) {
    13. super(numberOfReplicas, nodes);
    14. }
    15. @Override
    16. protected String defineCircleKey(String node, int i) {
    17. if(i > 99){
    18. return node + &quot;-&quot; + i;
    19. }else if(i > 9){
    20. return node + &quot;-0&quot; + i;
    21. }else{
    22. return node + &quot;-00&quot; + i;
    23. }
    24. }
    25. @Override
    26. protected long defineHash(String key) {
    27. try {
    28. MessageDigest md5 = MessageDigest.getInstance(&quot;MD5&quot;);
    29. md5.update(key.getBytes(Charset.forName(&quot;UTF8&quot;)));
    30. byte[] digest = md5.digest();
    31. long hash = 0;
    32. for (int i = 0; i < 4; i++) {
    33. hash += ((long) (digest[i * 4 + 3] & 0xFF) << 24)
    34. | ((long) (digest[i * 4 + 2] & 0xFF) << 16)
    35. | ((long) (digest[i * 4 + 1] & 0xFF) << 8)
    36. | ((long) (digest[i * 4 + 0] & 0xFF));
    37. }
    38. System.out.println(key+ &quot;--->&quot; + hash);
    39. return hash;
    40. } catch (Exception ex) {
    41. return -1;
    42. }
    43. }
    44. }
    复制代码
    # 完整案例(CRC32实现方式)这里是网Redis集群中写入数据,HashMap类型的数据
    1. package cn.yting.conhash;
    2. import java.io.BufferedReader;
    3. import java.io.InputStreamReader;
    4. import java.util.HashMap;
    5. import java.util.LinkedHashMap;
    6. import java.util.Map;
    7. import org.apache.commons.logging.Log;
    8. import org.apache.commons.logging.LogFactory;
    9. import redis.clients.jedis.Jedis;
    10. import redis.clients.jedis.JedisPool;
    11. import redis.clients.jedis.JedisPoolConfig;
    12. /**
    13. &#160;* 一致性哈希Utils, 实现了redis中hash的一般操作
    14. &#160;*&#160;
    15. &#160;* @Author 妳那伊抹微笑
    16. &#160;*
    17. &#160;*/
    18. public class ConsistentHashRedisUtils {
    19. <span style=&quot;white-space:pre&quot;></span>
    20. <span style=&quot;white-space:pre&quot;></span>/**
    21. <span style=&quot;white-space:pre&quot;></span> * redis server properties 配置文件的路径
    22. <span style=&quot;white-space:pre&quot;></span> */
    23. <span style=&quot;white-space:pre&quot;></span>private static final String REDIS_SERVERS_HANGZHOU_PROPERTIES = &quot;../../conf/analysis-redis-servers-hangzhou.properties&quot;;
    24. <span style=&quot;white-space:pre&quot;></span>/**
    25. <span style=&quot;white-space:pre&quot;></span> * 日志对象
    26. <span style=&quot;white-space:pre&quot;></span> */
    27. <span style=&quot;white-space:pre&quot;></span>private Log log = LogFactory.getLog(this.getClass());
    28. <span style=&quot;white-space:pre&quot;></span>
    29. <span style=&quot;white-space:pre&quot;></span>/**
    30. <span style=&quot;white-space:pre&quot;></span> * 一致性哈希
    31. <span style=&quot;white-space:pre&quot;></span> */
    32. <span style=&quot;white-space:pre&quot;></span>private AbstractConsistentHash hash;
    33. <span style=&quot;white-space:pre&quot;></span>
    34. <span style=&quot;white-space:pre&quot;></span>/**
    35. <span style=&quot;white-space:pre&quot;></span> * Redis连接池
    36. <span style=&quot;white-space:pre&quot;></span> */
    37. <span style=&quot;white-space:pre&quot;></span>private Map<String, JedisPool> jedisPools = new HashMap<String, JedisPool>();;
    38. <span style=&quot;white-space:pre&quot;></span>
    39. <span style=&quot;white-space:pre&quot;></span>/**
    40. <span style=&quot;white-space:pre&quot;></span> * 外网地址到内网地IP映射
    41. <span style=&quot;white-space:pre&quot;></span> */
    42. <span style=&quot;white-space:pre&quot;></span>private Map<String, String> redisNodeMaps = new LinkedHashMap<String, String>();
    43. <span style=&quot;white-space:pre&quot;></span>
    44. <span style=&quot;white-space:pre&quot;></span>/**
    45. <span style=&quot;white-space:pre&quot;></span> * 是否转换到内网地址创建jedis对象
    46. <span style=&quot;white-space:pre&quot;></span> */
    47. <span style=&quot;white-space:pre&quot;></span>private boolean isConvertIp = false;
    48. <span style=&quot;white-space:pre&quot;></span>
    49. <span style=&quot;white-space:pre&quot;></span>/**
    50. <span style=&quot;white-space:pre&quot;></span> * 虚拟节点个数
    51. <span style=&quot;white-space:pre&quot;></span> */
    52. <span style=&quot;white-space:pre&quot;></span>private static int numberOfReplicas = 8;
    53. <span style=&quot;white-space:pre&quot;></span>public ConsistentHashRedisUtils() {
    54. <span style=&quot;white-space:pre&quot;></span>this(numberOfReplicas);
    55. <span style=&quot;white-space:pre&quot;></span>}
    56. <span style=&quot;white-space:pre&quot;></span>
    57. <span style=&quot;white-space:pre&quot;></span>public ConsistentHashRedisUtils(int numberOfReplicas) {
    58. <span style=&quot;white-space:pre&quot;></span>redisNodeMaps = getRedisConfNodeMaps();
    59. <span style=&quot;white-space:pre&quot;></span>hash = new CRC32ConsistentHash(numberOfReplicas, redisNodeMaps.keySet());
    60. <span style=&quot;white-space:pre&quot;></span>}
    61. <span style=&quot;white-space:pre&quot;></span>/**
    62. <span style=&quot;white-space:pre&quot;></span> * hset
    63. <span style=&quot;white-space:pre&quot;></span> *&#160;
    64. <span style=&quot;white-space:pre&quot;></span> * @param key
    65. <span style=&quot;white-space:pre&quot;></span> * @param field
    66. <span style=&quot;white-space:pre&quot;></span> * @param value
    67. <span style=&quot;white-space:pre&quot;></span> */
    68. <span style=&quot;white-space:pre&quot;></span>public void hset(String key, String field, String value) {
    69. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = null;
    70. <span style=&quot;white-space:pre&quot;></span>Jedis jedis = null;
    71. <span style=&quot;white-space:pre&quot;></span>try {
    72. <span style=&quot;white-space:pre&quot;></span>pool = getJedisPool(key);
    73. <span style=&quot;white-space:pre&quot;></span>jedis = pool.getResource();
    74. <span style=&quot;white-space:pre&quot;></span>jedis.hset(key, field, value);
    75. <span style=&quot;white-space:pre&quot;></span>} catch (Exception e) {
    76. <span style=&quot;white-space:pre&quot;></span>log.error(&quot;Redis hset exception : &quot; + key, e);
    77. <span style=&quot;white-space:pre&quot;></span>pool.returnBrokenResource(jedis);
    78. <span style=&quot;white-space:pre&quot;></span>} finally {
    79. <span style=&quot;white-space:pre&quot;></span>pool.returnResource(jedis);
    80. <span style=&quot;white-space:pre&quot;></span>}
    81. <span style=&quot;white-space:pre&quot;></span>}
    82. <span style=&quot;white-space:pre&quot;></span>
    83. <span style=&quot;white-space:pre&quot;></span>/**
    84. <span style=&quot;white-space:pre&quot;></span> * hincrBy
    85. <span style=&quot;white-space:pre&quot;></span> *&#160;
    86. <span style=&quot;white-space:pre&quot;></span> * @param key
    87. <span style=&quot;white-space:pre&quot;></span> * @param field
    88. <span style=&quot;white-space:pre&quot;></span> * @param value
    89. <span style=&quot;white-space:pre&quot;></span> */
    90. <span style=&quot;white-space:pre&quot;></span>public void hincrBy(String key, String field, long value) {
    91. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = null;
    92. <span style=&quot;white-space:pre&quot;></span>Jedis jedis = null;
    93. <span style=&quot;white-space:pre&quot;></span>try {
    94. <span style=&quot;white-space:pre&quot;></span>pool = getJedisPool(key);
    95. <span style=&quot;white-space:pre&quot;></span>jedis = pool.getResource();
    96. <span style=&quot;white-space:pre&quot;></span>jedis.hincrBy(key, field, value);
    97. <span style=&quot;white-space:pre&quot;></span>} catch (Exception e) {
    98. <span style=&quot;white-space:pre&quot;></span>log.error(&quot;Redis hincrBy exception : &quot; + key, e);
    99. <span style=&quot;white-space:pre&quot;></span>pool.returnBrokenResource(jedis);
    100. <span style=&quot;white-space:pre&quot;></span>} finally {
    101. <span style=&quot;white-space:pre&quot;></span>pool.returnResource(jedis);
    102. <span style=&quot;white-space:pre&quot;></span>}
    103. <span style=&quot;white-space:pre&quot;></span>}
    104. <span style=&quot;white-space:pre&quot;></span>/**
    105. <span style=&quot;white-space:pre&quot;></span> * hget
    106. <span style=&quot;white-space:pre&quot;></span> *&#160;
    107. <span style=&quot;white-space:pre&quot;></span> * @param key
    108. <span style=&quot;white-space:pre&quot;></span> * @param field
    109. <span style=&quot;white-space:pre&quot;></span> * @return&#160;
    110. <span style=&quot;white-space:pre&quot;></span> */
    111. <span style=&quot;white-space:pre&quot;></span>public String hget(String key, String field) {
    112. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = null;
    113. <span style=&quot;white-space:pre&quot;></span>Jedis jedis = null;
    114. <span style=&quot;white-space:pre&quot;></span>String result = null;
    115. <span style=&quot;white-space:pre&quot;></span>
    116. <span style=&quot;white-space:pre&quot;></span>try {
    117. <span style=&quot;white-space:pre&quot;></span>pool = getJedisPool(key);
    118. <span style=&quot;white-space:pre&quot;></span>jedis = pool.getResource();
    119. <span style=&quot;white-space:pre&quot;></span>result = jedis.hget(key, field);
    120. <span style=&quot;white-space:pre&quot;></span>} catch (Exception e) {
    121. <span style=&quot;white-space:pre&quot;></span>log.error(&quot;Redis hget exception : &quot; + key, e);
    122. <span style=&quot;white-space:pre&quot;></span>pool.returnBrokenResource(jedis);
    123. <span style=&quot;white-space:pre&quot;></span>} finally {
    124. <span style=&quot;white-space:pre&quot;></span>pool.returnResource(jedis);
    125. <span style=&quot;white-space:pre&quot;></span>}
    126. <span style=&quot;white-space:pre&quot;></span>return result;
    127. <span style=&quot;white-space:pre&quot;></span>}
    128. <span style=&quot;white-space:pre&quot;></span>
    129. <span style=&quot;white-space:pre&quot;></span>/**
    130. <span style=&quot;white-space:pre&quot;></span> * hgetAll
    131. <span style=&quot;white-space:pre&quot;></span> *&#160;
    132. <span style=&quot;white-space:pre&quot;></span> * @param key
    133. <span style=&quot;white-space:pre&quot;></span> * @return map
    134. <span style=&quot;white-space:pre&quot;></span> */
    135. <span style=&quot;white-space:pre&quot;></span>public Map<String, String> hgetAll(String key) {
    136. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = null;
    137. <span style=&quot;white-space:pre&quot;></span>Jedis jedis = null;
    138. <span style=&quot;white-space:pre&quot;></span>Map<String, String> result = null;
    139. <span style=&quot;white-space:pre&quot;></span>
    140. <span style=&quot;white-space:pre&quot;></span>try {
    141. <span style=&quot;white-space:pre&quot;></span>pool = getJedisPool(key);
    142. <span style=&quot;white-space:pre&quot;></span>jedis = pool.getResource();
    143. <span style=&quot;white-space:pre&quot;></span>result = jedis.hgetAll(key);
    144. <span style=&quot;white-space:pre&quot;></span>} catch (Exception e) {
    145. <span style=&quot;white-space:pre&quot;></span>log.error(&quot;Redis hgetAll exception : &quot; + key, e);
    146. <span style=&quot;white-space:pre&quot;></span>pool.returnBrokenResource(jedis);
    147. <span style=&quot;white-space:pre&quot;></span>} finally {
    148. <span style=&quot;white-space:pre&quot;></span>pool.returnResource(jedis);
    149. <span style=&quot;white-space:pre&quot;></span>}
    150. <span style=&quot;white-space:pre&quot;></span>return result;
    151. <span style=&quot;white-space:pre&quot;></span>}
    152. <span style=&quot;white-space:pre&quot;></span>
    153. <span style=&quot;white-space:pre&quot;></span>/**
    154. <span style=&quot;white-space:pre&quot;></span> * hdel
    155. <span style=&quot;white-space:pre&quot;></span> *&#160;
    156. <span style=&quot;white-space:pre&quot;></span> * @param key
    157. <span style=&quot;white-space:pre&quot;></span> * @param field
    158. <span style=&quot;white-space:pre&quot;></span> */
    159. <span style=&quot;white-space:pre&quot;></span>public void hdel(String key, String field) {
    160. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = null;
    161. <span style=&quot;white-space:pre&quot;></span>Jedis jedis = null;
    162. <span style=&quot;white-space:pre&quot;></span>try {
    163. <span style=&quot;white-space:pre&quot;></span>pool = getJedisPool(key);
    164. <span style=&quot;white-space:pre&quot;></span>jedis = pool.getResource();
    165. <span style=&quot;white-space:pre&quot;></span>jedis.hdel(key, field);
    166. <span style=&quot;white-space:pre&quot;></span>} catch (Exception e) {
    167. <span style=&quot;white-space:pre&quot;></span>log.error(&quot;Redis hdel exception : &quot; + key, e);
    168. <span style=&quot;white-space:pre&quot;></span>pool.returnBrokenResource(jedis);
    169. <span style=&quot;white-space:pre&quot;></span>} finally {
    170. <span style=&quot;white-space:pre&quot;></span>pool.returnResource(jedis);
    171. <span style=&quot;white-space:pre&quot;></span>}
    172. <span style=&quot;white-space:pre&quot;></span>}
    173. <span style=&quot;white-space:pre&quot;></span>/**
    174. <span style=&quot;white-space:pre&quot;></span> * 通过userid获取对应的jedis连接
    175. <span style=&quot;white-space:pre&quot;></span> *&#160;
    176. <span style=&quot;white-space:pre&quot;></span> * @param userid
    177. <span style=&quot;white-space:pre&quot;></span> * @return
    178. <span style=&quot;white-space:pre&quot;></span> * @throws Exception
    179. <span style=&quot;white-space:pre&quot;></span> */
    180. <span style=&quot;white-space:pre&quot;></span>private JedisPool getJedisPool(String userid) throws Exception {
    181. <span style=&quot;white-space:pre&quot;></span>String key = this.hash.getNode(userid);
    182. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = this.jedisPools.get(key);
    183. <span style=&quot;white-space:pre&quot;></span>if (pool == null) {
    184. <span style=&quot;white-space:pre&quot;></span>String outKey = key;
    185. <span style=&quot;white-space:pre&quot;></span>/*
    186. <span style=&quot;white-space:pre&quot;></span> * 将外网ip转换内网ip
    187. <span style=&quot;white-space:pre&quot;></span> */
    188. <span style=&quot;white-space:pre&quot;></span>if (this.isConvertIp) {
    189. <span style=&quot;white-space:pre&quot;></span>key = this.redisNodeMaps.get(key);
    190. <span style=&quot;white-space:pre&quot;></span>if (key == null) {
    191. <span style=&quot;white-space:pre&quot;></span>throw new Exception(&quot;not &quot; + key + &quot; in redisNodeMaps&quot;);
    192. <span style=&quot;white-space:pre&quot;></span>}
    193. <span style=&quot;white-space:pre&quot;></span>}
    194. <span style=&quot;white-space:pre&quot;></span>String[] host_port = key.split(&quot;:&quot;);
    195. <span style=&quot;white-space:pre&quot;></span>pool = getJedisPool(host_port);
    196. <span style=&quot;white-space:pre&quot;></span>log.info(&quot;-------------------->Redis ip--->port : &quot; + host_port[0] + &quot;--->&quot; + host_port[1]);
    197. <span style=&quot;white-space:pre&quot;></span>this.jedisPools.put(outKey, pool);
    198. <span style=&quot;white-space:pre&quot;></span>}
    199. <span style=&quot;white-space:pre&quot;></span>return pool;
    200. <span style=&quot;white-space:pre&quot;></span>}
    201. <span style=&quot;white-space:pre&quot;></span>/**
    202. <span style=&quot;white-space:pre&quot;></span> * 获得redis的连接池
    203. <span style=&quot;white-space:pre&quot;></span> *&#160;
    204. <span style=&quot;white-space:pre&quot;></span> * @param host_port
    205. <span style=&quot;white-space:pre&quot;></span> * @return
    206. <span style=&quot;white-space:pre&quot;></span> */
    207. <span style=&quot;white-space:pre&quot;></span>private JedisPool getJedisPool(String[] host_port) {
    208. <span style=&quot;white-space:pre&quot;></span>JedisPoolConfig config = new JedisPoolConfig();
    209. <span style=&quot;white-space:pre&quot;></span>config.setMaxActive(500);
    210. <span style=&quot;white-space:pre&quot;></span>config.setMaxIdle(10);
    211. <span style=&quot;white-space:pre&quot;></span>config.setMaxWait(3000000);
    212. <span style=&quot;white-space:pre&quot;></span>config.setTestOnBorrow(true);
    213. <span style=&quot;white-space:pre&quot;></span>config.setTestOnReturn(true);
    214. <span style=&quot;white-space:pre&quot;></span>return new JedisPool(config, host_port[0], Integer.parseInt(host_port[1]));
    215. <span style=&quot;white-space:pre&quot;></span>}
    216. <span style=&quot;white-space:pre&quot;></span>/**
    217. <span style=&quot;white-space:pre&quot;></span> * 关闭所有redis链接
    218. <span style=&quot;white-space:pre&quot;></span> */
    219. <span style=&quot;white-space:pre&quot;></span>public void closeAllConnection() throws Exception {
    220. <span style=&quot;white-space:pre&quot;></span>for (String key : this.jedisPools.keySet()) {
    221. <span style=&quot;white-space:pre&quot;></span>JedisPool pool = this.jedisPools.get(key);
    222. <span style=&quot;white-space:pre&quot;></span>
    223. <span style=&quot;white-space:pre&quot;></span>if (pool != null) {
    224. <span style=&quot;white-space:pre&quot;></span>pool.destroy();
    225. <span style=&quot;white-space:pre&quot;></span>}
    226. <span style=&quot;white-space:pre&quot;></span>}
    227. <span style=&quot;white-space:pre&quot;></span>}
    228. <span style=&quot;white-space:pre&quot;></span>
    229. <span style=&quot;white-space:pre&quot;></span>/**
    230. <span style=&quot;white-space:pre&quot;></span> * 从配置文件中获取Redis集群的IP
    231. <span style=&quot;white-space:pre&quot;></span> *&#160;
    232. <span style=&quot;white-space:pre&quot;></span> * @return
    233. <span style=&quot;white-space:pre&quot;></span> */
    234. <span style=&quot;white-space:pre&quot;></span>private Map<String, String> getRedisConfNodeMaps(){
    235. <span style=&quot;white-space:pre&quot;></span> Map<String, String> rmaps = null;
    236. <span style=&quot;white-space:pre&quot;></span> String line = null;
    237. <span style=&quot;white-space:pre&quot;></span> try {
    238. <span style=&quot;white-space:pre&quot;></span>BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(REDIS_SERVERS_HANGZHOU_PROPERTIES)));
    239. <span style=&quot;white-space:pre&quot;></span>rmaps = new LinkedHashMap<String, String>();
    240. <span style=&quot;white-space:pre&quot;></span>String[] splits = null;
    241. <span style=&quot;white-space:pre&quot;></span>String outIp = null;
    242. <span style=&quot;white-space:pre&quot;></span>String inIp = null;
    243. <span style=&quot;white-space:pre&quot;></span>while((line=reader.readLine())!=null){
    244. <span style=&quot;white-space:pre&quot;></span>if(line.trim().length() <5 || line.trim().startsWith(&quot;#&quot;)) continue;
    245. <span style=&quot;white-space:pre&quot;></span>log.info(&quot;redis server : &quot; + line);
    246. <span style=&quot;white-space:pre&quot;></span>splits = line.split(&quot; +|\t+&quot;);
    247. <span style=&quot;white-space:pre&quot;></span>outIp = splits[0];
    248. <span style=&quot;white-space:pre&quot;></span>inIp = splits[1];
    249. <span style=&quot;white-space:pre&quot;></span>rmaps.put(outIp, inIp);
    250. <span style=&quot;white-space:pre&quot;></span>}
    251. <span style=&quot;white-space:pre&quot;></span>log.info(&quot;ConsistentHashRedisUtils initialize configure ../../conf/analysis-redis-servers-hangzhou.properties is successful ...&quot;);
    252. <span style=&quot;white-space:pre&quot;></span>} catch (Exception e) {
    253. <span style=&quot;white-space:pre&quot;></span>log.error(&quot;ConsistentHashRedisUtils initialize error : &quot; + line, e);
    254. <span style=&quot;white-space:pre&quot;></span>}
    255. <span style=&quot;white-space:pre&quot;></span>return rmaps;
    256. <span style=&quot;white-space:pre&quot;></span>}
    257. <span style=&quot;white-space:pre&quot;></span>
    258. }
    复制代码
    redis-servers.properties 参考的配置文件,这里是外网转内网的IP,读者可以自行修改一下、、、
    1. # redis servers
    2. 20.20.20.234:6379 192.168.1.109:6379
    3. 20.20.20.234:6380 192.168.1.109:6380
    4. 20.20.20.234:6381 192.168.1.109:6381
    5. 20.20.20.235:6379 192.168.1.110:6379
    6. 20.20.20.235:6380 192.168.1.110:6380
    7. 20.20.20.235:6381 192.168.1.110:6381
    8. 20.20.20.236:6379 192.168.1.111:6379
    9. 20.20.20.236:6380 192.168.1.111:6380
    10. 20.20.20.236:6381 192.168.1.111:6381
    11. 20.20.20.237:6379 192.168.1.112:6379
    12. 20.20.20.237:6380 192.168.1.112:6380
    13. 20.20.20.237:6381 192.168.1.112:6381
    14. 20.20.20.238:6379 192.168.1.113:6379
    15. 20.20.20.238:6380 192.168.1.113:6380
    16. 20.20.20.238:6381 192.168.1.113:6381
    17. 20.20.20.239:6379 192.168.1.114:6379
    18. 20.20.20.239:6380 192.168.1.114:6380
    19. 20.20.20.239:6381 192.168.1.114:6381
    20. 20.20.20.243:6379 192.168.1.127:6379
    21. 20.20.20.243:6380 192.168.1.127:6380
    22. 20.20.20.243:6381 192.168.1.127:6381
    23. 20.20.20.243:6382 192.168.1.127:6382
    24. 20.20.20.243:6383 192.168.1.127:6383
    25. 20.20.20.243:6384 192.168.1.127:6384
    26. 20.20.20.243:6385 192.168.1.127:6385
    27. 20.20.20.243:6386 192.168.1.127:6386
    28. 20.20.20.244:6379 192.168.1.128:6379
    29. 20.20.20.244:6380 192.168.1.128:6380
    30. 20.20.20.244:6381 192.168.1.128:6381
    31. 20.20.20.245:6379 192.168.1.129:6379
    32. 20.20.20.245:6380 192.168.1.129:6380
    33. 20.20.20.245:6381 192.168.1.129:6381
    34. 20.20.20.246:6379 192.168.1.130:6379
    35. 20.20.20.246:6380 192.168.1.130:6380
    36. 20.20.20.246:6381 192.168.1.130:6381
    37. 20.20.20.247:6379 192.168.1.131:6379
    38. 20.20.20.247:6380 192.168.1.131:6380
    39. 20.20.20.247:6381 192.168.1.131:6381
    40. 20.20.20.248:6379 192.168.1.132:6379
    41. 20.20.20.248:6380 192.168.1.132:6380
    42. 20.20.20.248:6381 192.168.1.132:6381
    43. 20.20.20.249:6379 192.168.1.133:6379
    44. 20.20.20.249:6380 192.168.1.133:6380
    45. 20.20.20.249:6381 192.168.1.133:6381
    复制代码
    到了这里也就告一段落了,现在来说下一开始的那几个问题吧!1、减少节点以上的代码还没有解决数据转移的问题,比如其中一台Redis服务器挂掉了,应该将数据转移到该服务器顺时针最近的那一台活着的服务器上去,而且以后数据恢复,还需要自己写代码做数据校验,数据找回等等!!!这也是一个麻烦的问题 、、、(至少数据不会丢失了,这点还是不错的,数据校验跟数据找回的代码写好后,也可以一劳永逸了,嘎嘎!)2、增加节点
    由于使用了虚拟节点的方式,上面的虚拟节点数量为8,现在新增一台Redis服务器,也会虚拟出8台虚拟节点出来,这里原先假设的是有12台Redis服务器,假如现在的这8台虚拟节点如果刚好分布到了其他8台虚拟节点之间,也就是意味着另外8台Redis中差不多每台Rdis服务器都会有八分之一的数据会跑到现在新增的这台Redis服务器上,这样也会造成数据混乱,这该如何解决 、、、也就是新增节点之后还是破坏了原有的映射关系,当然知道了这样的原理之后也是可以写代码数据校验跟找回的,重新平衡服务器的数据,不过那也太麻烦点了,伤不起啊!假如这里虚拟节点的数据变大了,那以后增加节点是不是要做的工作就更大了,这 、、、
    综上所述,一致性哈希这个理论虽然不错,但是想要完美的实现出来还是要点时间的,重点就是数据校验跟数据找回了,不会有人把这样完美的成果给发到网上吧,这 、、、、、、   
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-20 10:00 , Processed in 0.401923 second(s), 54 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表