码迷,mamicode.com
首页 > 编程语言 > 详细

负载均衡算法(二)加权轮询负载均衡算法

时间:2016-08-02 16:39:15      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

    /// <summary>
    /// 加权轮询算法
    /// </summary>
    public static class WeightRoundRobin
    {
        private static object obj = new object();
        private static int pos = 0;

        static Dictionary<string, int> dic = new Dictionary<string, int>
        {
            { "192.168.1.12", 1},
            {"192.168.1.13", 1 },
            { "192.168.1.14", 3},
            { "192.168.1.15", 1},
            {"192.168.1.16", 1},
            {"192.168.1.17", 1 },
            { "192.168.1.18", 1},
            { "192.168.1.19", 1}
        };

        public static string roundRobin()
        {
            //獲取ip列表list
            List<string> it = dic.Keys.ToList();

            List<String> serverList = new List<string>();

            foreach (var item in it)
            {
                int weight = 0;
                dic.TryGetValue(item, out weight);

                for (int i = 0; i < weight; i++)
                {
                    serverList.Add(item);
                }
            }

            string server = null;

            lock (obj)
            {
                if (pos >= serverList.Count)
                {
                    pos = 0;
                }
                server = serverList[pos];
                pos++;
            }
            return server;
        }

    }

 

负载均衡算法(二)加权轮询负载均衡算法

标签:

原文地址:http://www.cnblogs.com/liyangLife/p/5729386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!