第五周命题作业
// 服务器节点
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);
}
// 一致性 hash(hash 环,虚拟节点)
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();
}
@Override
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);
});
}
@Override
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);
});
}
@Override
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());
}
}
评论