负载均衡算法(三)加权随机负载均衡算法

    /// <summary>
    /// 加权随机负载均衡算法
    /// </summary>
    public static class WeightRandom
    {

        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 weightRandom()
        {
            //獲取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);
                }
            }
            Random random = new Random();
            int randomPos = random.Next(serverList.Count);
            string server = serverList[randomPos];
            return server;
        }
    }
原文地址:https://www.cnblogs.com/liyangLife/p/5729392.html