package hash;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
* @description:
* @author: liu.w
* @create: 2020-07-06 10:47
**/
public class ConsistentHashingWithVirtualNode {
private static final int p = 16777619;
* 100万key
*/
private static final int total = 1000000;
* 虚拟节点,key表示虚拟节点的hash值,value表示虚拟节点的名称
*/
private static SortedMap<Integer, String> virtualNodes = new TreeMap<>();
* 虚拟节点与真实节点的映射,key表示虚拟节点的hash值,value表示真实节点index
*/
private static final SortedMap<Integer, Integer> serverMap = new TreeMap<>();
* key真实节点index-缓存key数量
*/
private static final Map<Integer, Integer> dataMap = new HashMap<>();
* 初始虚拟节点与真实节点的映射
* @param serverNum
* @param nodeNum
*/
private static void init(int serverNum, int nodeNum) {
serverMap.clear();
virtualNodes.clear();
dataMap.clear();
for (int i = 0; i < serverNum; i++) {
dataMap.put(i, 0);
for (int j = 0; j < nodeNum; j++) {
String virtualNodeName = "server" + i + "&&VN" + j;
int hash = getHash(virtualNodeName);
serverMap.put(hash, i);
virtualNodes.put(hash, virtualNodeName);
}
}
}
* 使用FNV1_32_HASH算法计算服务器的Hash值,这里不使用重写hashCode的方法,最终效果没区别
*/
private static int getHash(String str) {
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 = Math.abs(hash);
}*/
return hash;
}
* 得到key应当路由到的真实结点
*/
private static Integer getServer(String key) {
int hash = getHash(key);
SortedMap<Integer, Integer> subMap = serverMap.tailMap(hash);
if (subMap.isEmpty()) {
subMap = serverMap;
}
Integer i = subMap.firstKey();
return subMap.get(i);
}
* 生成随机Key
*
* @param length
* @return
*/
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
public static void run(Set<String> strings, int serverNum, int nodeNum) {
init(serverNum, nodeNum);
for (String string : strings) {
Integer serverIndex = getServer(string);
dataMap.put(serverIndex, dataMap.getOrDefault(serverIndex, 0) + 1);
}
int avg = total / serverNum;
double variance = dataMap.values().stream().mapToLong(x -> (avg - x) * (avg - x)).average().getAsDouble();
int sqrt = (int) Math.sqrt(variance);
System.out.println("虚拟节点数:"+nodeNum + " 方差:" + variance + " 标准差:" + sqrt);
}
public static void main(String[] args) {
Set<String> set = new HashSet<>(total);
for (int i = 0; i < total; i++) {
set.add(getRandomString(10));
}
run(set, 10, 50);
run(set, 10, 100);
run(set, 10, 150);
run(set, 10, 200);
run(set, 10, 300);
run(set, 10, 500);
run(set, 10, 1000);
}
}
评论