package com.lsl.test.hash;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* 分布式缓存一致性hash算法,带虚拟节点
* @author lisl
*
*/
public class HashCacheTest2 {
private static final String [] realServers =
{"192.168.1.100","192.168.1.101", "192.168.1.102", "192.168.1.103", "192.168.1.104"};
//真实主机
private static List<String> realNodeList = new LinkedList<String>();
//虚拟主机,key表示主机hash值,value为虚拟主机名称
private static SortedMap<Integer, String> sortMap = new TreeMap<Integer, String>();
private static final Integer virtualNodeNumber = 5;
static{
for (int i = 0; i < realServers.length; i++) {
realNodeList.add(realServers[i]);
//每个主机添加对应数量的虚拟节点
for (int j = 0; j < virtualNodeNumber; j++) {
String virtualNodeName = realServers[i]+"@v"+j;
sortMap.put(getHash(virtualNodeName), virtualNodeName);
System.out.println("虚拟主机初始化:"+virtualNodeName);
}
}
}
private static String getServer(String keyWord){
SortedMap<Integer, String> tailMap = sortMap.tailMap(getHash(keyWord));
String virtualServerName = "";
if(tailMap != null && tailMap.size() > 0){
virtualServerName = tailMap.get(tailMap.firstKey());
}else{
virtualServerName = sortMap.get(sortMap.firstKey());
}
return virtualServerName.substring(0, virtualServerName.indexOf("@"));
}
private static Integer getHash(String keyWord){
final int p = 16777619;
int hash = (int)2166136261L;
for (int i = 0; i < keyWord.length(); i++)
hash = (hash ^ keyWord.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;
}
/**
* @param args
*/
public static void main(String[] args) {
String [] dataStrs = {"香蕉王", "好人网", "水蜜桃", "苹果纸", "句大的子"};
for (int j = 0; j < dataStrs.length; j++) {
System.out.println(dataStrs[j]+"被分配到"+getServer(dataStrs[j]));
}
}
}
分布式缓存一致性hash算法,带虚拟节点
最新推荐文章于 2024-06-29 16:51:42 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)