使用循环调度算法进行负载调度?

8

我需要编写一个轮询算法来调度n个端点的负载?

如果我有A、B和C服务器

我想确保每次收到请求时都通过它们进行轮询。我如何在C#中实现这一点?


1
这将是恒定负载还是您希望负载均衡? - Avitus
我认为“轮询”表示没有尝试平均分配负载。 - H H
3个回答

24

我想质疑那些声称想要实现轮询的人,看看他们是否真的了解轮询。 - Tim
2
它经常用于服务器负载分配。 - kemiller2002
4
当使用这种模式时,立即将服务器加入队列可能是值得的(或将其放在finally块中进行排队)。这样,在“使用”服务器期间抛出的任何异常都不会导致服务器被完全从轮换中移除。 - bvoyelr
这应该被包装在一个类中。 - JJS
链表比队列更好,不需要重新排队项目,只需从头开始 :) - VisualBean

8
与 ebpower 相同的想法,但是关注的是下一项是什么,而不是下一项的索引。
public class RoundRobinList<T>
{
    private readonly IList<T> _list;
    private readonly int _size;
    private int _position;

    public RoundRobinList(IList<T> list)
    {
        if (!list.Any())
            throw new NullReferenceException("list");

        _list = new List<T>(list);
        _size = _list.Count;            
    }

    public T Next()
    {
        if (_size == 1)
            return _list[0];

        Interlocked.Increment(ref _position);
        var mod = _position % _size;
        return _list[mod];
    }
}

1
将IEnumerable<T>传递给构造函数,在递增_position之前记录mod,这就是金钱。 - JJS
1
Interlocked.Increment will reach int.MaxValue in very high load scenarios. In that case, it handles the overflow condition and returns int.MinValue as per documentation and this code will throw an System.ArgumentOutOfRangeException while accessing the array because of the negative index. A simple check can handle it: ... Interlocked.Increment(ref _position); if(_position == Int32.MinValue) { Interlocked.Exchange(ref _position, 0); } ... - SalvatoreGarrubba
另一种实现方式是在到达列表末尾时重置位置:https://gist.github.com/randyburden/251f0514f893013d711da1b4e395aaa5 - Randy Burden

2
如果您的端点是通过列表或数组访问的,您只需要以循环方式递增索引:
public class RoundRobinIndex
{
    volatile int index = 0;
    int count;

    public int Next
    {
        get
        {
            if (index == count)
            {
                index = 0;
            } 
            return index++;
        }
    }

    public RoundRobinIndex(int countArg)
    {
        count = countArg;
    }
}

使用它将导致IndexOutOfRangeException异常。 - SnIcK
@IBootstrap - 它不会导致 IndexOutOfRangeException。您是否确实测试过它? - Ed Power
下一个也可以通过以下方式实现:(index + 1) % count; - Aerokneeus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接