本文实例为大家分享了C#实现Nginx平滑加权轮询算法的具体代码,供大家参考,具体内容如下
代码很简单,算法很经典!
1. 定义实体类
1
2
3
4
5
6
7
8
9
10
11
|
public struct ServerConfig
{
//初始权重
public int Weight { get ; set ;}
//当前权重
public int Current { get ; set ;}
//服务名称
public string Name { get ; set ;}
}
|
2. 算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public static int NextServerIndex(ServerConfig[] serverConfigArray)
{
int index = -1;
int total = 0;
int size = serverConfigArray.Count();
for ( int i = 0; i< size; i++)
{
serverConfigArray[i].Current += serverConfigArray[i].Weight;
total += serverConfigArray[i].Weight;
if (index == -1 || serverConfigArray[index].Current < serverConfigArray[i].Current)
{
index = i;
}
}
serverConfigArray[index].Current -= total;
return index;
}
|
3.调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
static void Main( string [] args)
{
var sv = new ServerConfig[] {
new ServerConfig{Name= "A" , Weight = 4},
new ServerConfig{Name= "B" , Weight = 2},
new ServerConfig{Name= "C" , Weight = 1}
};
int index = 0;
int sum = sv.Sum(m => m.Weight);
for ( int i=0; i<sum; i++)
{
index = NextServerIndex(sv);
Console.WriteLine( "{0}{1}" , sv[index].Name, sv[index].Weight);
}
Console.Read();
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/gangle/p/9358175.html