今天在看《大型分布式網站架構設計與實踐》一書中, 看到了一種比較簡單的加權的算法, 在這里記下來:
var serverWeightMap = new Dictionary<string, int>();
serverWeightMap.Add("192.168.1.100", 1);
serverWeightMap.Add("192.168.1.101", 1);
// 權重為 4
serverWeightMap.Add("192.168.1.102", 4);
serverWeightMap.Add("192.168.1.103", 1);
serverWeightMap.Add("192.168.1.104", 1);
// 權重為 3
serverWeightMap.Add("192.168.1.105", 3);
serverWeightMap.Add("192.168.1.106", 1);
// 權重為 2
serverWeightMap.Add("192.168.1.107", 2);
serverWeightMap.Add("192.168.1.108", 1);
serverWeightMap.Add("192.168.1.109", 1);
serverWeightMap.Add("192.168.1.110", 1);
int pos = 0;
// 加權輪詢
public static string getRoundRobin()
{
List<string> ipList = new List<string>();
foreach(var key in serverWeightMap.Keys)
{
var weight = serverWeightMap[key];
for(var i = 0; i < weight; i++)
ipList.Add(key);
}
var ip = string.Empty;
lock(pos)
{
if(pos > ipList.Count)
pos = 0;
ip = ipList[pos];
pos++;
}
return ip;
}
// 加權隨機
public static string getRandom()
{
List<string> ipList = new List<string>();
foreach(var key in serverWeightMap.Keys)
{
var weight = serverWeightMap[key];
for(var i = 0; i < weight; i++)
ipList.Add(key);
}
var randPos = Convert.ToInt32((new Random()).Next(ipList.Count));
var ip = ipList[randPos];
return ip;
}
上面的兩個方法中, 就處理服務器 IP 地址的時候, 根據權重的不同, 在 IP 列表中重復添加 IP 值,權重越大, IP 列表中 IP 值的重復數就越多。
