一致性哈希 java代码实例
时间: 2023-07-31 14:04:38 浏览: 138
一致性hashjava实现
以下是一致性哈希的 Java 代码实现,以字符串的哈希值作为节点的标识:
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class ConsistentHash {
private final MessageDigest md5;
private final int numberOfReplicas;
private final SortedMap<Long, String> circle = new TreeMap<>();
public ConsistentHash(int numberOfReplicas) {
try {
this.md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm not available");
}
this.numberOfReplicas = numberOfReplicas;
}
public void addNode(String node) {
for (int i = 0; i < numberOfReplicas; i++) {
String replicaKey = getReplicaKey(node, i);
long hash = hashKey(replicaKey);
circle.put(hash, node);
}
}
public void removeNode(String node) {
for (int i = 0; i < numberOfReplicas; i++) {
String replicaKey = getReplicaKey(node, i);
long hash = hashKey(replicaKey);
circle.remove(hash);
}
}
public String getNode(String key) {
if (circle.isEmpty()) {
return null;
}
long hash = hashKey(key);
if (!circle.containsKey(hash)) {
SortedMap<Long, String> tailMap = circle.tailMap(hash);
hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
}
return circle.get(hash);
}
private String getReplicaKey(String node, int i) {
return node + ":" + i;
}
private long hashKey(String key) {
md5.reset();
md5.update(key.getBytes());
byte[] digest = md5.digest();
long h = 0;
for (int i = 0; i < 4; i++) {
h <<= 8;
h |= ((int) digest[i]) & 0xFF;
}
return h;
}
}
```
以下是一个简单的测试:
```java
ConsistentHash consHash = new ConsistentHash(100);
consHash.addNode("node1");
consHash.addNode("node2");
consHash.addNode("node3");
System.out.println(consHash.getNode("key1")); // 输出 node1
System.out.println(consHash.getNode("key2")); // 输出 node2
consHash.removeNode("node2");
System.out.println(consHash.getNode("key1")); // 输出 node1
System.out.println(consHash.getNode("key2")); // 输出 node3
```
以上代码实现了一致性哈希的基本功能,包括添加节点、删除节点、根据键值获取节点等。
阅读全文