按权重值轮训算法
标签:readonly read ext void balance server else 输出 lock
轮训算法:
///
/// 轮训算法
///
public class WeightBalance
{
private static readonly object LockObject = new object();
private WeightBalance() { }
static WeightBalance()
{
Instance = new WeightBalance();
}
public static WeightBalance Instance
{
get;
private set;
}
public T Next(List list) where T : IWeightItem
{
if (list == null || !list.Any())
{
throw new ArgumentNullException(nameof(list));
}
if (list.Count == 1)
{
return list.First();
}
lock (LockObject)
{
int total = list.Sum(i => i.Weight);
int maxIndex = 0;
int maxValue = 0;
int weight = 0;
for (int i = 0; i )
{
if (list[i].Attach != 0)
{
weight = list[i].Attach;
}
else
{
weight = list[i].Weight;
list[i].Attach = weight;
}
if (i == 0)
{
maxValue = weight;
}
else if (weight > maxValue)
{
maxIndex = i;
maxValue = weight;
}
}
list[maxIndex].Attach = list[maxIndex].Attach - total;
return list[maxIndex];
}
}
}
///
/// 被轮询的实体要实现此接口
///
public interface IWeightItem
{
///
/// 权重值
///
int Weight { get; set; }
///
/// 附加值
///
int Attach { get; set; }
}
客户端:
class Program
{
static void Main(string[] args)
{
var connectionList = new List{
new SlaveConnection{ ConnectionString="server=.;Database=2;",Weight=2},
new SlaveConnection{ ConnectionString="server=.;Database=5;",Weight=5},
new SlaveConnection{ ConnectionString="server=.;Database=1;",Weight=1},
new SlaveConnection{ ConnectionString="server=.;Database=3;",Weight=3},
new SlaveConnection{ ConnectionString="server=.;Database=4;",Weight=4},
};
for (int i = 0; i 30; i++)
{
Console.WriteLine(WeightBalance.Instance.Next(connectionList).ConnectionString);
}
Console.ReadKey();
}
}
public class SlaveConnection : IWeightItem
{
public string ConnectionString { get; set; }
public int Weight { get; set; }
public int Attach { get; set; }
}
输出结果:
按权重值轮训算法
标签:readonly read ext void balance server else 输出 lock
原文地址:https://www.cnblogs.com/fanfan-90/p/12862705.html
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
按权重值轮训算法
文章链接:http://soscw.com/index.php/essay/46638.html
评论