---
title: "带虚拟节点的一致性哈希"
author: "blackbeans"
date: "2011-07-20T23:09:30Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-10-25T23:03:08Z"
id: 1129256
url: "https://blackbeans.iteye.com/blog/1129256"
---

```
将物理节点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);
    }

 
```