实现加权轮询负载均衡思路
代码实现一个加权负载均衡
Weight 初始化时对节点约定的权重
currentWeight 节点临时权重,每轮都会变化
effectiveWeight 节点有效权重,默认与Weight相同
totalWeight 所有节点有效权重之和:sum(effectiveWeight)
代码实现一个加权负载均衡
currentWeight = currentWeight+effecitveWeight
选中最大的 currentWeight 节点为选中节点
currentWeight = currentWeight-totalWeight (4+3+2=9)
所以我们能够 在表格模拟运行情况:
加权轮询负载均衡代码
测试代码
测试结果
$gotest2021/06/1819:17:57Failedtoconnectto127.0.0.1:2181:dialtcp127.0.0.1:2181:i/otimeout127.0.0.1:2003127.0.0.1:2005127.0.0.1:2003127.0.0.1:2003127.0.0.1:2005127.0.0.1:2003127.0.0.1:2003127.0.0.1:2003127.0.0.1:2005127.0.0.1:2003127.0.0.1:2005127.0.0.1:2003127.0.0.1:2003127.0.0.1:2005127.0.0.1:2003127.0.0.1:2003127.0.0.1:2003127.0.0.1:2003127.0.0.1:2005PASSokgateway/pratise/proxy/load_balance1.124s
从测试结果我们可以看出,2003 为 2005 的两倍,符合权重设置结果