平滑的加权轮询
前言
如何“优雅的轮询”,是生产环境中很常见一种场景,
所谓“优雅”,即在均衡分配的基础上,要保证连续的请求不能连续分配到某一个后端节点上;
可以理解为时间上的连续请求,要尽量分配到物理上的不同节点,避免某段时间内后端单台节点压力过大。
算法描述
On each peer selection we increase current_weight of each eligible peer by its weight, Select peer with greatest current_weight and reduce its current_weight by total number of weight points distributed among peers.
代码实现
type Node struct {
Name string
Current int
Weight int
}
func SmoothWrr(nodes []*Node) (best *Node) {
if len(nodes) == 0 {
return
}
total := 0
for _, node := range nodes {
if node == nil {
continue
}
total += node.Weight
node.Current += node.Weight
if best == nil || node.Current > best.Current {
best = node
}
}
if best == nil {
return
}
best.Current -= total
return
}
func main() {
nodes := []*Node{
&Node{"a", 0, 5},
&Node{"b", 0, 1},
&Node{"c", 0, 1},
}
for i := 0; i < 7; i++ {
best := SmoothWrr(nodes)
if best != nil {
fmt.Println(best.Name)
}
}
}
代码转自 nginx平滑的基于权重轮询算法分析
作者:Standby — 一生热爱名山大川、草原沙漠,还有我们小郭宝贝!
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号