架构师训练营第五周作业
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
/*Dht*/
public class Dht {
private int numOfServers;
private int numOfVirtualNodesPerServer;
private TreeMap<Integer, Node> nodes;
public Dht(int numOfServers, int numOfVirtualNodesPerServer) {
this.numOfServers = numOfServers;
this.numOfVirtualNodesPerServer = numOfVirtualNodesPerServer;
nodes = new TreeMap<>();
initServer();
}
private void initServer() {
for (int i = 0; i < numOfServers; i++) {
for (int j = 0; j < numOfVirtualNodesPerServer; j++) {
Node node = new Node(i,j);
nodes.put(node.getNodeHashKey(),node);
}
}
}
public int[] getDistribution() {
int[] distribution = new int[numOfServers];
for (Map.Entry<Integer, Node> node : nodes.entrySet()){
distribution[node.getValue().getServerNo()] += node.getValue().getCount();
}
return distribution;
}
public void distribute(int[] data) {
for (int i = 0; i < data.length; i++) {
int hashCode = Hash.getHash(data[i] + "");
Map.Entry<Integer, Node> entry = (entry = nodes.ceilingEntry(hashCode)) != null ? entry : nodes.firstEntry();
entry.getValue().cache(i, data[i]);
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/*Node*/
public class Node {
private int nodeNo;
private int serverNo;
private int nodeHashKey;
private Map<Integer,Integer> values = new HashMap<>(1000);
public int getServerNo() {
return serverNo;
}
public int getNodeHashKey() {
return nodeHashKey;
}
public Node(int serverNo, int nodeNo) {
this.serverNo = serverNo;
this.nodeNo = nodeNo;
this.nodeHashKey = Hash.getHash("server" + this.serverNo + "#" + String.format("%3d", this.nodeNo));
}
public void cache(int key, int value) {
values.put(key, value);
}
public int getCount() {
return values.size();
}
}
/*Hash algorithm*/
public class Hash {
public static int getHash(String str) {
final int p = 16777619;
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;
}
}
/*Test*/
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
public class DhtTest {
private int[] data = new int[1000000];
@Before
public void setUp() {
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
}
@Test
public void testDht() {
Dht dht = new Dht(10, 100);
dht.distribute(data);
int[] count = dht.getDistribution();
System.out.println(Arrays.toString(count));
}
}
版权声明: 本文为 InfoQ 作者【James-Pang】的原创文章。
原文链接:【http://xie.infoq.cn/article/62fafbe058878da7c6317ac84】。未经作者许可,禁止转载。
评论