如果❤️我的文章有帮助,欢迎点赞、关注。这是对我继续技术创作最大的鼓励。[更多系列文章在我博客] https://coderdao.github.io/
Golang 实现加权轮询负载均衡
实现加权轮询负载均衡思路
代码实现一个加权负载均衡
- Weight 初始化时对节点约定的权重
- currentWeight 节点临时权重,每轮都会变化
- effectiveWeight 节点有效权重,默认与Weight相同
- totalWeight 所有节点有效权重之和:sum(effectiveWeight)
代码实现一个加权负载均衡
- currentWeight = currentWeight+effecitveWeight
- 选中最大的 currentWeight 节点为选中节点
- currentWeight = currentWeight-totalWeight (4+3+2=9)
所以我们能够 在表格模拟运行情况:
请求次数 | 请求前currentWelght | 选中的节点 | 请求后currentWelght |
---|---|---|---|
1 | [serverA=4,serverB=3,serverC=2] | serverA | [serverA=-1,serverB=6,serverC=4] |
2 | [serverA=-1,serverB=6,serverC=4] | serverB | [serverA=3,serverB=0,serverC=6] |
3 | [serverA=3,serverB=0,serverC=6] | serverc | [serverA=7,serverB=3,serverC=-1] |
4 | [serverA=7,serverB=3,serverC=-1] | serverA | [serverA=2,serverB=6,serverC=1] |
5 | [serverA=2,serverB=6,serverC=1] | serverB | [serverA=6,serverB=0,serverC=3] |
6 | [serverA=6,serverB=0,serverC=3] | serverA | [serverA=1,serverB=3,serverC=5] |
7 | [serverA=1,serverB=3,serverC=5] | serverc | [serverA=5,serverB=6,serverC=-2] |