架构训练营第五周作业
public class Node {
private String domain;
private String ip;
private Map<String, Object> data;
public <T> void put(String key, T value) {
data.put(key, value);
}
public void remove(String key){
data.remove(key);
}
public <T> T get(String key) {
return (T) data.get(key);
}
}
public abstract class Cluster {
protected List<Node> nodes;
public Cluster() {
this.nodes = new ArrayList<>();
}
public abstract void addNode(Node node);
public abstract void removeNode(Node node);
public abstract Node get(String key);
}
public class NormalHashCluster extends Cluster {
public NormalHashCluster() {
super();
}
public void addNode(Node node) {
this.nodes.add(node);
}
public void removeNode(Node node) {
this.nodes.removeIf(o -> o.getIp().equals(node.getIp()) ||
o.getDomain().equals(node.getDomain()));
}
public Node get(String key) {
long hash = hash(key);
long index = hash % nodes.size();
return nodes.get((int)index);
}
}
Cluster cluster = new NormalHashCluster();
cluster.addNode(new Node("c1.info", "192.168.0.1"));
cluster.addNode(new Node("c2.info", "192.168.0.2"));
cluster.addNode(new Node("c3.info", "192.168.0.3"));
cluster.addNode(new Node("c4.info", "192.168.0.4"));
IntStream.range(0, DATA_COUNT)
.forEach(index -> {
Node node = cluster.get(PRE_KEY + index);
node.put(PRE_KEY + index, "Test Data");
});
System.out.println("数据分布情况:");
cluster.nodes.forEach(node -> {
System.out.println("IP:" + node.getIp() + ",数据量:" + node.getData().size());
});
//缓存命中率
long hitCount = IntStream.range(0, DATA_COUNT)
.filter(index -> cluster.get(PREKEY + index).get(PREKEY + index) != null)
.count();
System.out.println("缓存命中率:" + hitCount * 1f / DATA_COUNT);
public class ConsistencyHashCluster extends Cluster {
private SortedMap<Long, Node> virNodes = new TreeMap<Long, Node>();
private static final int VIRNODECOUNT = 512;
private static final String SPLIT = "#";
public ConsistencyHashCluster() {
super();
}
public void addNode(Node node) {
this.nodes.add(node);
IntStream.range(0, VIRNODECOUNT)
.forEach(index -> {
long hash = hash(node.getIp() + SPLIT + index);
virNodes.put(hash, node);
});
}
public void removeNode(Node node) {
nodes.removeIf(o -> node.getIp().equals(o.getIp()));
IntStream.range(0, VIRNODECOUNT)
.forEach(index -> {
long hash = hash(node.getIp() + SPLIT + index);
virNodes.remove(hash);
});
}
public Node get(String key) {
long hash = hash(key);
SortedMap<Long, Node> subMap = hash >= virNodes.lastKey() ? virNodes.tailMap(0L) : virNodes.tailMap(hash);
if (subMap.isEmpty()) {
return null;
}
return subMap.get(subMap.firstKey());
}
}
评论