C# 实现 Nginx 平滑加权轮询算法
代码很简单,算法很经典!
1. 定义实体类
public struct ServerConfig { //初始权重 public int Weight {get;set;} //当前权重 public int Current {get;set;} //服务名称 public string Name {get;set;} }
2. 算法
// 找出数组中当前权重最小的那个服务的index,并把那个服务的当前权重减去总权重。
public static int NextServerIndex(ServerConfig[] serverConfigArray) { int index = -1; int totalWeight = 0; int size = serverConfigArray.Count(); for(int i = 0; i< size; i++) { serverConfigArray[i].Current += serverConfigArray[i].Weight; totalWeight += serverConfigArray[i].Weight; if (index == -1 || serverConfigArray[index].Current < serverConfigArray[i].Current) { index = i; } } serverConfigArray[index].Current -= totalWeight; return index; }
3.调用
public static void TestServerAssignment() { //构建三台服务器 var servers = new ServerConfig[] { new ServerConfig{Name="A", Weight = 4}, new ServerConfig{Name="B", Weight = 2}, new ServerConfig{Name="C", Weight = 1} }; int beUsedIndex = 0; int sum = servers.Sum(m => m.Weight); //总权重 //模拟调用服务次数为总权重数 for(int i=0; i<sum; i++) { beUsedIndex = NextServerIndex(servers); Console.WriteLine("Current Server is {0}, its weight is {1}", servers[beUsedIndex].Name, servers[beUsedIndex].Weight); } }
4.运行结果