zoukankan      html  css  js  c++  java
  • C# Nginx平滑加权轮询算法

    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 { getset; }

        /// <summary>

        /// 当前权重

        /// </summary>

        public int Current { getset; }

        /// <summary>

        /// 服务名称

        /// </summary>

        public string Name { getset; }

    }

      

    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

          转载请注名出处,谢谢!  

  • 相关阅读:
    python2 类型转换和数值操作
    python2 实现的LED大数字效果
    Python2 基础语法(三)
    delphi操作ini文件
    [SQL]数据库还原 42000错误
    我的宝宝来了
    [DELPHI] D2009控件的安装
    DELPHI学习过程和函数
    [SQL][转载]SQL优化索引
    [SQL] SQL语句,存储过程执行时间
  • 原文地址:https://www.cnblogs.com/grj001/p/12224878.html
Copyright © 2011-2022 走看看