平滑的加权轮询

 


前言

如何“优雅的轮询”,是生产环境中很常见一种场景,

所谓“优雅”,即在均衡分配的基础上,要保证连续的请求不能连续分配到某一个后端节点上;

可以理解为时间上的连续请求,要尽量分配到物理上的不同节点,避免某段时间内后端单台节点压力过大。

算法描述

1
2
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. 

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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平滑的基于权重轮询算法分析

posted @   RainingInMacondo  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示