Round-Robin轮询调度法及其实现原理 加权轮询算法 Round Robin算法的简单C#实现 权重轮询调度算法(Weighted Round-Robin Scheduling)-C#实现 三种常用的负载均衡算法C#(随机、轮询、权重)
应用场景,是要根据权重给多个队列均匀的提供数据,对输入的数据进行拆分处理。
最核心的部分,其实是取最大公约数。
using System;
using System.Collections.Generic;
using RoundRobin;
public class MyClass
{
public static void RunSnippet()
{
List<Node> servers = new List<Node>();
servers.Add(new Node("serv","urlA",1));
servers.Add(new Node("serv","urlB",1));
servers.Add(new Node("serv","urlC",4));
Dictionary<string,List<int>> dictLog = new Dictionary<string,List<int>>();
RoundRobinBalancer balancer = new RoundRobinBalancer(servers);
for(int i = 1;i<=100;i++){
Node node = balancer.DispatchTo();
if(!dictLog.ContainsKey(node.Url))
dictLog[node.Url] = new List<int>();
dictLog[node.Url].Add(i);
}
foreach(string key in dictLog.Keys){
WL("Url:{0} ==> {1}",key,dictLog[key].Count);
}
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
namespace RoundRobin{
public class Node{
public Node(string serviceName,string url,int weight){
this.ServiceName = serviceName;
this.Url = url;
this.Weight = weight;
}
public int Weight{get;private set;}
public string Url{get;private set;}
public string ServiceName{get;private set;}
}
public class RoundRobinBalancer{
private readonly List<Node> nodes;
private int i = -1;
private int cw = 0;
public RoundRobinBalancer(List<Node> nodes){
this.nodes = nodes;
}
public Node DispatchTo(){
while(true){
i = (i+1)%nodes.Count;
if(i==0){
cw = cw - MaxCommonDivisor(nodes);
if(cw <= 0){
cw = MaxWeight(nodes);
if(cw == 0)
return null;
}
}
if((nodes[i]).Weight >= cw)
return nodes[i];
}
}
private static int MaxCommonDivisor(List<Node> nodes){
List<int> nums = new List<int>();
foreach(Node node in nodes)
{
nums.Add(node.Weight);
}
return max_common_divisor(nums);
}
private static int MaxWeight(List<Node> nodes){
int ret = -1;
foreach(Node node in nodes){
if(node.Weight>ret)
ret = node.Weight;
}
return ret;
}
public static int gcd(int n, int m)
{
//swap
if (n<m)
{
n=m+n;
m=n-m;
n=n-m;
}
if (m==0) return n;
return gcd(m,n%m);
}
public static int max_common_divisor(List<int> several)
{
int a=several[0];
int b=several[1];
int c=gcd(a,b);
int i;
for (i=2; i<several.Count; i++)
{
c=gcd(c,several[i]);
}
return c;
}
}
}