ITeye博客

带虚拟节点的一致性哈希

blackbeans · 2011-07-20 23:09 · 算法 · 编程语言 · Markdown

将物理节点hash和虚拟节点形成映射
    private void hash() {
        /**
        *  将物理节点散列成虚拟节点
        * */
        for (INode node : this.physicalNodes) {

            for (int i = 0; i < virtualCount / 4; i++) {

                byte[] hashCodeBytes = (node.getKey().toString() + i).getBytes();

                hashCodeBytes = Utils.md5Encode(hashCodeBytes);


                for (int j = 0; j < 4; j++) {

                    int virtualKey = (hashCodeBytes[3 + 4 * j] & 0xFF) << 24 | (hashCodeBytes[2 + 4 * j] & 0xFF) << 16 | (hashCodeBytes[1 + 4 * j] & 0xFF) << 8 |
                            (hashCodeBytes[4 * j] & 0xFF);

                    this.sortedHashNode.put(virtualKey, node);

                }

            }
        }

    }

给定Key查找数据的物理节点逻辑
   /**
     * 这里是用来给定一个key来通过虚拟节点定位到于物理节点的逻辑
     *
     * @param key
     * @return
     */
    public INode locate(Key key) {

        int virtualKey = key.key2VirtualKey();

        if (!this.sortedHashNode.containsKey(virtualKey)) {

            SortedMap<Integer, INode> sortedNodes = this.sortedHashNode.tailMap(virtualKey);


            if (sortedNodes.isEmpty()) {

                virtualKey = this.sortedHashNode.firstKey();
            } else {

                virtualKey = sortedNodes.firstKey();
            }

        }


        return this.sortedHashNode.get(virtualKey);
    }

 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。