平滑的加权轮询
前言
如何“优雅的轮询”,是生产环境中很常见一种场景,
所谓“优雅”,即在均衡分配的基础上,要保证连续的请求不能连续分配到某一个后端节点上;
可以理解为时间上的连续请求,要尽量分配到物理上的不同节点,避免某段时间内后端单台节点压力过大。
算法描述
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平滑的基于权重轮询算法分析
作者:Standby — 一生热爱名山大川、草原沙漠,还有我们小郭宝贝!
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通