需求:如何将请求按照权值 分配给服务器。
大致思想:需要两个全局变量currentWeight 初始化为最大权值 和currentIndex 初始化为0 。从currentIndex开始遍历 找到索引对应Node权值大于等于currentWeight 时候返回Node的ip,同时若currentIndex = currentIndex + 1 后为服务器总数即越界,那么需要重置currentIndex = 0;同时判断currentWeight = currnetWeight - max 更新后的值是否为0,如果为0 则需要将currentWeight = 最大权值。
public class WeightRoundRobbin {
private static int currentWeight = -1,currentIndex = 0;
private static final List<Node> nodes = new ArrayList<>();
private static int max = -1;//最大公约数
static {
nodes.add(new Node("ip1",4));
nodes.add(new Node("ip2",8));
nodes.add(new Node("ip3",16));
Collections.sort(nodes, (Node o1,Node o2)->{
return o1.weight - o2.weight;
});
currentWeight = nodes.get(nodes.size() - 1).weight;
max = getMaxDivide(nodes);//获取最大公约数
}
public static void main(String[] args) {
for(int i = 0;i<28;i++){
System.out.println(getServer());

本文介绍了权重轮询负载均衡算法,通过两个全局变量实现服务器请求分配,并讨论了一致性哈希在分布式缓存系统中的作用,以减少因节点增删导致的缓存失效问题。同时,提到了缓存穿透、缓存雪崩等现象及其解决方案,如使用布隆过滤器和设置不同过期时间。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



