帮我用Java写一个一致性哈希算法
时间: 2023-08-04 10:39:19 浏览: 168
好的,以下是一个简单的Java实现一致性哈希算法的示例代码:
```java
import java.util.*;
public class ConsistentHash {
// 哈希环中节点的数量
private int nodeCount;
// 虚拟节点的数量
private int replicaCount;
// 哈希环
private SortedMap<Integer, String> hashCircle = new TreeMap<>();
public ConsistentHash(int nodeCount, int replicaCount, List<String> nodes) {
this.nodeCount = nodeCount;
this.replicaCount = replicaCount;
for (String node : nodes) {
addNode(node);
}
}
// 添加节点
public void addNode(String node) {
for (int i = 0; i < replicaCount; i++) {
int hash = getHash(node + i);
hashCircle.put(hash, node);
}
}
// 删除节点
public void removeNode(String node) {
for (int i = 0; i < replicaCount; i++) {
int hash = getHash(node + i);
hashCircle.remove(hash);
}
}
// 获取节点
public String getNode(String key) {
if (hashCircle.isEmpty()) {
return null;
}
int hash = getHash(key);
if (!hashCircle.containsKey(hash)) {
// 获取大于等于当前哈希值的第一个节点
SortedMap<Integer, String> tailMap = hashCircle.tailMap(hash);
hash = tailMap.isEmpty() ? hashCircle.firstKey() : tailMap.firstKey();
}
return hashCircle.get(hash);
}
// 获取哈希值
private 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;
hash &= 0x7fffffff;
return hash;
}
}
```
使用示例:
```java
public static void main(String[] args) {
List<String> nodes = Arrays.asList("node1", "node2", "node3");
ConsistentHash consistentHash = new ConsistentHash(nodes.size(), 3, nodes);
for (int i = 0; i < 10; i++) {
String key = "key" + i;
String node = consistentHash.getNode(key);
System.out.println(key + " -> " + node);
}
}
```
输出结果:
```
key0 -> node3
key1 -> node3
key2 -> node1
key3 -> node3
key4 -> node1
key5 -> node2
key6 -> node3
key7 -> node1
key8 -> node2
key9 -> node1
```
这里的一致性哈希算法使用的是MurmurHash算法,可以保证哈希值的平衡性和随机性。在实际应用中,可以根据具体的需求进行调整和优化。
阅读全文