写点什么

week05 作业

用户头像
Geek_196d0f
关注
发布于: 2020 年 07 月 08 日

一致性hash算法,代码实现。采用步骤:1、初始化环大小为100万 2、初始化10个真实节点 3、初始化1024个虚拟节点,虚拟节点取hashcode对100万求余映射到环上。4、测试0到100万个数字字符串,负载到真实节点的情况

运行结果:

代码:

public class Test {
static class RealNode {
int index;
String ip;
int port;
int count;
public RealNode(int index, String ip, int port){
this.index = index;
this.ip = ip;
this.port = port;
}
public void count() {
this.count ++;
}
public int getCount() {
return this.count;
}
public int getIndex() {
return this.index;
}
}
static class VirtualNode{
int index;
RealNode realNode;
public VirtualNode(int index, RealNode realNode){
this.index = index;
this.realNode = realNode;
}
public RealNode getRealNode(){
return this.realNode;
}
}
public static void main(String[] args) {
// 初始化环长度为100万
VirtualNode[] hashCircle = new VirtualNode[1000000];
//生成10个虚拟节点
RealNode[] nodes = {new RealNode(0, "127.0.0.1", 8001),
new RealNode(1, "127.0.0.1", 8002),
new RealNode(2, "127.0.0.1", 8003),
new RealNode(3, "127.0.0.1", 8004),
new RealNode(4, "127.0.0.1", 8005),
new RealNode(5, "127.0.0.1", 8006),
new RealNode(6, "127.0.0.1", 8007),
new RealNode(7, "127.0.0.1", 8008),
new RealNode(8, "127.0.0.1", 8009),
new RealNode(9, "127.0.0.1", 8010),
};
// 生成1024个虚拟节点
for(int i = 0; i< 1024; i++){
VirtualNode virtualNode = new VirtualNode(i, nodes[i%10]);
hashCircle[virtualNode.hashCode()%1000000] = virtualNode;
}
// 测试100万数据
for(int i = 0; i < 1000000; i++){
RealNode node = findNode(String.valueOf(i).hashCode(), hashCircle);
node.count();
}
// 输出结果,展示标准差
for(RealNode node : nodes){
System.out.println("编号:" + node.getIndex() + ", 命中:" + node.getCount());
}
}
public static RealNode findNode(int hashcode, VirtualNode[] hashCircle){
for(int i = hashcode%1000000; i < hashCircle.length; i++){
if(hashCircle[i] != null){
return hashCircle[i].getRealNode();
}
//如果i等于环的最大值时,则重置i等于0,只到找到为止
if(i == hashCircle.length - 1){
i = 0;
}
}
return null;
}
}



用户头像

Geek_196d0f

关注

还未添加个人签名 2018.09.06 加入

还未添加个人简介

评论

发布
暂无评论
week05 作业