【轉】C# Nginx平滑加權輪詢算法

 

代碼很簡單,但算法很經典,話不多說,直接上代碼。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public struct ServerConfig
{
    /// <summary>
    /// 初始權重
    /// </summary>
    public int Weight { get; set; }
    /// <summary>
    /// 當前權重
    /// </summary>
    public int Current { get; set; }
    /// <summary>
    /// 服務名稱
    /// </summary>
    public string Name { get; set; }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static int NextServerIndex(ServerConfig[] ss)
{
    int index = -1;
    int total = 0;
    int size = ss.Count();   
 
    for (int i = 0; i < size; i++)
    {
        ss[i].Current += ss[i].Weight;
        total += ss[i].Weight;
 
        if (index == -1 || ss[index].Current < ss[i].Current)
        {
            index = i;
        }
    }
 
    ss[index].Current -= total;
    return index;
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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();
}

  參考文獻:http://blog.csdn.net/gqtcgq/article/details/52076997

      文章出處:http://www.cnblogs.com/anech/p/6704240.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章