一致性hash算法

介绍

http://blog.csdn.net/cywosp/article/details/23397179/

http://www.cnblogs.com/haippy/archive/2011/12/10/2282943.html

http://blog.csdn.net/caigen1988/article/details/7708806

http://www.blogjava.net/hello-yun/archive/2012/10/10/389289.html

 

java 实现

http://www.iteye.com/topic/1132274

http://blog.csdn.net/wuhuan_wp/article/details/7010071

http://www.oschina.net/code/snippet_730640_22941

思路

1 定义一个Hash算法

2 定义一个Map,以IP等作为key,hash出N个key复本作为Key(value为真实的节点)存入Map

      for (int i = 0; i < numberOfReplicas; i++) {
                    circle.put(hashFunc.hash(node.toString() + i), node);
                }

3取值:hash传入的值,Map.get(hash(key)),如果没有,取tailMap的第一个key,再Map.get(hash(key))

        public T get(Object key) {
            readReadWriteLock.readLock().lock();
            try{
                if (circle.isEmpty()) {
                    return null;
                }
                int hash = hashFunc.hash(key);
                if (!circle.containsKey(hash)) {
                    SortedMap<Integer, T> tailMap = circle.tailMap(hash); // 返回此映射的部分视图,其键大于等于
                    hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
                }
                // 正好命中
                return circle.get(hash);
            }finally{
                readReadWriteLock.readLock().unlock();
            }
        }

posted @ 2015-11-24 10:15  穿林度水  阅读(171)  评论(0编辑  收藏  举报