第五周 - 作业一
import java.util.HashMap;
import java.util.TreeMap;
import java.util.UUID;
public class ConsistentHash {
public static TreeMap<Integer, String> nodesMap = new TreeMap<Integer, String>();
public static void init() {
String[] nodes = new String[]{"192.168.1.0", "192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4",
"192.168.1.5", "192.168.1.6", "192.168.1.7", "192.168.1.8", "192.168.1.9",};
for (String node : nodes) {
for(int i=0;i<15;i++){
//System.out.println(getHash(node+"#"+i));
nodesMap.put(getHash(node+"#"+i), node);
}
}
}
public static void addNode(String node) {
nodesMap.put(getHash(node), node);
}
public static void dropNode(String node) {
nodesMap.remove(getHash(node));
}
public static String getNode(String key) {
if(null==nodesMap.ceilingEntry(getHash(key))){
return nodesMap.firstEntry().getValue();
}
return nodesMap.ceilingEntry(getHash(key)).getValue();
}
private static int getHash(String str) {
final int p = 16777619;
int hash = (int) 2166136261L;
//System.out.println(hash);
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;
// 如果算出来的值为负数则取其绝对值
if (hash < 0) {
hash = Math.abs(hash);
}
return hash;
}
public static void main(String[] args) {
init();
HashMap<String,Integer> count=new HashMap<String,Integer>();
for(int i=0;i<100000;i++){
String uuid= UUID.randomUUID().toString().replace("-","");
String node=getNode(uuid);
if(count.containsKey(node)){
count.replace(node,count.get(node)+1);
}else{
count.put(node,1);
}
}
System.out.println(count);
}
}
评论