zoukankan      html  css  js  c++  java
  • 一致性Hash算法

    import java.util.Collection;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.SortedMap;
    import java.util.SortedSet;
    import java.util.TreeMap;
    import java.util.TreeSet;

    public class ConsistentHash<T> {
    private final HashFunction hashFunction;
    private final int numberOfReplicas;// 节点的复制因子,实际节点个数 * numberOfReplicas =
    // 虚拟节点个数
    private final SortedMap<Long, T> circle = new TreeMap<Long, T>();// 存储虚拟节点的hash值到真实节点的映射

    public ConsistentHash(HashFunction hashFunction, int numberOfReplicas, Collection<T> nodes) {
    this.hashFunction = hashFunction;
    this.numberOfReplicas = numberOfReplicas;
    for (T node : nodes)
    add(node);
    }

    public void add(T node) {
    for (int i = 0; i < numberOfReplicas; i++)
    // 对于一个实际机器节点 node, 对应 numberOfReplicas 个虚拟节点
    /*
    * 不同的虚拟节点(i不同)有不同的hash值,但都对应同一个实际机器node 虚拟node一般是均衡分布在环上的,数据存储在顺时针方向的虚拟node上
    */
    circle.put(hashFunction.hash(node.toString() + i), node);
    }

    public void remove(T node) {
    for (int i = 0; i < numberOfReplicas; i++)
    circle.remove(hashFunction.hash(node.toString() + i));
    }

    /*
    * 获得一个最近的顺时针节点,根据给定的key 取Hash 然后再取得顺时针方向上最近的一个虚拟节点对应的实际节点 再从实际节点中取得 数据
    */
    public T get(Object key) {
    if (circle.isEmpty())
    return null;
    long hash = hashFunction.hash((String) key);// node 用String来表示,获得node在哈希环中的hashCode
    if (!circle.containsKey(hash)) {// 数据映射在两台虚拟机器所在环之间,就需要按顺时针方向寻找机器
    SortedMap<Long, T> tailMap = circle.tailMap(hash);
    hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
    }
    return circle.get(hash);
    }

    public long getSize() {
    return circle.size();
    }

    /*
    * 查看MD5算法生成的hashCode值---表示整个哈希环中各个虚拟节点位置
    */
    public void testBalance() {
    Set<Long> sets = circle.keySet();// 获得TreeMap中所有的Key
    SortedSet<Long> sortedSets = new TreeSet<Long>(sets);// 将获得的Key集合排序
    for (Long hashCode : sortedSets) {
    System.out.println(hashCode);
    }

    System.out.println("----each location 's distance are follows: ----");
    /*
    * 查看用MD5算法生成的long hashCode 相邻两个hashCode的差值
    */
    Iterator<Long> it = sortedSets.iterator();
    Iterator<Long> it2 = sortedSets.iterator();
    if (it2.hasNext())
    it2.next();
    long keyPre, keyAfter;
    while (it.hasNext() && it2.hasNext()) {
    keyPre = it.next();
    keyAfter = it2.next();
    System.out.println(keyAfter - keyPre);
    }
    }

    public static void main(String[] args) {
    Set<String> nodes = new HashSet<String>();
    nodes.add("A");
    nodes.add("B");
    nodes.add("C");

    ConsistentHash<String> consistentHash = new ConsistentHash<String>(new HashFunction(), 2, nodes);
    consistentHash.add("D");

    System.out.println("hash circle size: " + consistentHash.getSize());
    System.out.println("location of each node are follows: ");
    consistentHash.testBalance();
    }

    }

    。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

    。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;

    /*
    * 实现一致性哈希算法中使用的哈希函数,使用MD5算法来保证一致性哈希的平衡性
    */
    public class HashFunction {
    private MessageDigest md5 = null;

    public long hash(String key) {
    if (md5 == null) {
    try {
    md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException("no md5 algrithm found");
    }
    }

    md5.reset();
    md5.update(key.getBytes());
    byte[] bKey = md5.digest();
    // 具体的哈希函数实现细节--每个字节 & 0xFF 再移位
    long result = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16 | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF));
    return result & 0xffffffffL;
    }
    }

    // MessageDigest的功能及用法  https://www.cnblogs.com/honey01/p/6420111.html

     // 注解  https://www.cnblogs.com/wzhanke/p/4562056.html

    /** 

    1.      * 字节数组到long的转换. 
    2.      */  
    3.     public static long byteToLong(byte[] b) {  
    4.         long s = 0;  
    5.         long s0 = b[0] & 0xff;// 最低位  
    6.         long s1 = b[1] & 0xff;  
    7.         long s2 = b[2] & 0xff;  
    8.         long s3 = b[3] & 0xff;  
    9.         long s4 = b[4] & 0xff;// 最低位  
    10.         long s5 = b[5] & 0xff;  
    11.         long s6 = b[6] & 0xff;  
    12.         long s7 = b[7] & 0xff;  
    13.   
    14.         // s0不变  
    15.         s1 <<= 8;  
    16.         s2 <<= 16;  
    17.         s3 <<= 24;  
    18.         s4 <<= 8 * 4;  
    19.         s5 <<= 8 * 5;  
    20.         s6 <<= 8 * 6;  
    21.         s7 <<= 8 * 7;  
    22.         s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;  
    23.         return s;  
    24.     }  
  • 相关阅读:
    算法练习(16)-水平翻转一颗二叉树
    算法练习(15)-设计1个二叉树的序列化与反序列化实现?
    算法练习(14)-二叉树中2个节点的最近公共祖先?
    算法练习(13)-打印纸条对折的折痕类型(凹痕?凸痕?)
    算法练习(12)-二叉树的递归套路
    算法练习(11)-二叉树的各种遍历
    算法练习(10)-求2个(可能有环的)单链表的相交节点
    算法练习(9)-复杂带随机指针的单链表
    mac升级后第三方下载程序无法打开cannot be opened because the developer cannot be verified的解决办法
    算法练习(8)-判断单链表是否回文链表
  • 原文地址:https://www.cnblogs.com/mybatis/p/9343070.html
Copyright © 2011-2022 走看看