架构师训练营第五周作业
发布于: 2020 年 10 月 25 日
用你熟悉的编程语言实现一致性 hash 算法。
这里使用基于虚拟节点的一致性Hash算法
import java.util.*;/** * 类说明: */public class ConsistentHash {    private static final int DEFAULT_NOTES = 5;    private static String[] servers = {"196.168.0.1:111","192.168.0.2.:111","192.168.0.3:111","192.168.0.4:111"};    private static SortedMap<Integer, String> virtualNodes = new TreeMap<>();    private static List<String> realNodes = new LinkedList<>();    static{        for (int i = 0; i < servers.length; i++) {            realNodes.add(servers[i]);        }        for (String str : realNodes) {            int realHash = getHash(str);            int realInterval = Integer.MAX_VALUE / DEFAULT_NOTES;            for (int i = 0; i < DEFAULT_NOTES; i++) {                String virtualNodeName = str + "&&VN" + String.valueOf(i);                int hash = (realHash + realInterval * i) & Integer.MAX_VALUE;                System.out.println("[" + virtualNodeName + "]加入集合中,其Hash值为:" + hash);                virtualNodes.put(hash, virtualNodeName);            }        }        System.out.println();    }    private static String getServer(String key){        int hash = getHash(key);        SortedMap<Integer, String> tailMap = virtualNodes.tailMap(hash);        if (tailMap.isEmpty()) {            long serverKey = virtualNodes.firstKey();            return virtualNodes.get(serverKey);        } else {            long serverKey = tailMap.firstKey();            return virtualNodes.get(serverKey);        }    }    /**     * 使用FNV1_32_HASH算法计算服务器的Hash值,这里不使用重写hashCode的方法,最终效果没区别     * 从网上借鉴的     */    private static int getHash(String str) {        final int p = 16777619;        int hash = (int) 2166136261L;        for (int i = 0; i < str.length(); i++) {            hash = (hash ^ str.charAt(i)) * p;        }        hash += hash << 13;        hash ^= hash >> 7;        hash += hash << 3;        hash ^= hash >> 17;        hash += hash << 5;        // 如果算出来的值为负数则取其绝对值        if (hash < 0) {            hash = Math.abs(hash);        }        return hash;    }}用你熟悉的编程语言实现一致性 hash 算法。
 划线
   评论
  复制
发布于: 2020 年 10 月 25 日 阅读数: 8
 
 月殇
  关注 
还未添加个人签名 2019.04.15 加入
还未添加个人简介
 
 
  
  
 
 
 
  
  
  
  
  
  
  
  
    
评论