平滑的加权轮询

前言

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

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

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

算法描述

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平滑的基于权重轮询算法分析

posted @ 2022-05-27 17:32  lixin[at]hitwh  阅读(73)  评论(0编辑  收藏  举报