consist_hash.java import java.nio.charset.Charset;import java.util.Collection;import java.util.SortedMap;import java.util.TreeMap;import com.google.common.hash.HashCode;import com.google.common.hash.HashFunction;public class ConsistentHash
import java.nio.charset.Charset; import java.util.Collection; import java.util.SortedMap; import java.util.TreeMap; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; public class ConsistentHash{ private final HashFunction hashFunction; private final int numberOfReplicas; private final SortedMap circle = new TreeMap (); public ConsistentHash(HashFunction hashFunction, int numberOfReplicas, Collection nodes) { this.hashFunction = hashFunction; this.numberOfReplicas = numberOfReplicas; for (T node : nodes) { add(node); } } public void add(T node) { for (int i = 0; i < numberOfReplicas; i++) { circle.put(hashFunction.hashString(node.toString() + i, Charset.defaultCharset()).asInt(), node); } } public void remove(T node) { for (int i = 0; i < numberOfReplicas; i++) { circle.remove(hashFunction.hashString(node.toString() + i, Charset.defaultCharset()).asInt()); } } public T get(Object key) { if (circle.isEmpty()) { return null; } HashCode hashCode = hashFunction.hashString((String) key, Charset.defaultCharset()); int hash = hashCode.asInt(); if (!circle.containsKey(hash)) { SortedMap tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); } return circle.get(hash); } }