整合性hashアルゴリズムjava実装
整合性hashアルゴリズムjava実装
import java.util.Collection;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Hash :http://blog.csdn.net/sparkliang/article/details/5279393
* :https://weblogs.java.net/blog/2007/11/27/consistent-hashing
*
* @author xiaoleilu
*
* @param
*
*/
public class ConsistentHash {
/** Hash , hash */
HashFunc hashFunc;
/** */
private final int numberOfReplicas;
/** Hash */
private final SortedMap circle = new TreeMap();
/**
* , Java Hash
*
* @param numberOfReplicas
* ,
* @param nodes
*
*/
public ConsistentHash(int numberOfReplicas, Collection nodes) {
this.numberOfReplicas = numberOfReplicas;
this.hashFunc = new HashFunc() {
public Integer hash(Object key) {
String data = key.toString();
// FNV1hash
final int p = 16777619;
int hash = (int) 2166136261L;
for (int i = 0; i < data.length(); i++)
hash = (hash ^ data.charAt(i)) * p;
hash += hash << 13;
hash ^= hash >> 7;
hash += hash << 3;
hash ^= hash >> 17;
hash += hash << 5;
return hash;
}
};
//
for (T node : nodes) {
add(node);
}
}
/**
*
*
* @param hashFunc
* hash
* @param numberOfReplicas
* ,
* @param nodes
*
*/
public ConsistentHash(HashFunc hashFunc, int numberOfReplicas,
Collection nodes) {
this.numberOfReplicas = numberOfReplicas;
this.hashFunc = hashFunc;
//
for (T node : nodes) {
add(node);
}
}
/**
*
* ,
* 2, , , Node
* hash node toString , toString
*
* @param node
*
*/
public void add(T node) {
for (int i = 0; i < numberOfReplicas; i++) {
circle.put(hashFunc.hash(node.toString() + i), node);
}
}
/**
*
*
* @param node
*
*/
public void remove(T node) {
for (int i = 0; i < numberOfReplicas; i++) {
circle.remove(hashFunc.hash(node.toString() + i));
}
}
/**
*
*
* @param key
* Hash,
* @return
*/
public T get(Object key) {
if (circle.isEmpty()) {
return null;
}
int hash = hashFunc.hash(key);
if (!circle.containsKey(hash)) {
SortedMap tailMap = circle.tailMap(hash); // ,
// hash
hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
}
//
return circle.get(hash);
}
/**
* Hash , hash
*
* @author xiaoleilu
*
*/
public interface HashFunc {
public Integer hash(Object key);
}
}