zoukankan      html  css  js  c++  java
  • 加权轮询和加权随机算法

    今天在看《大型分布式网站架构设计与实践》一书中, 看到了一种比较简单的加权的算法, 在这里记下来:

    var serverWeightMap = new Dictionary<string, int>();
    serverWeightMap.Add("192.168.1.100", 1);
    serverWeightMap.Add("192.168.1.101", 1);
    
    // 权重为 4
    serverWeightMap.Add("192.168.1.102", 4);
    serverWeightMap.Add("192.168.1.103", 1);
    serverWeightMap.Add("192.168.1.104", 1);
    
    // 权重为 3
    serverWeightMap.Add("192.168.1.105", 3);
    serverWeightMap.Add("192.168.1.106", 1);
    
    // 权重为 2
    serverWeightMap.Add("192.168.1.107", 2);
    serverWeightMap.Add("192.168.1.108", 1);
    serverWeightMap.Add("192.168.1.109", 1);
    serverWeightMap.Add("192.168.1.110", 1);
    
    
    int pos = 0;
    // 加权轮询
    public static string getRoundRobin()
    {
        List<string> ipList = new List<string>();
        foreach(var key in serverWeightMap.Keys)
        {
            var weight = serverWeightMap[key];
            for(var i = 0; i < weight; i++)
                ipList.Add(key);
        }
    
        var ip = string.Empty;
        lock(pos)
        {
            if(pos > ipList.Count)
                pos = 0;
    
            ip = ipList[pos];
            pos++;
        }
    
        return ip;
    }
    
    // 加权随机
    public static string getRandom()
    {
        List<string> ipList = new List<string>();
        foreach(var key in serverWeightMap.Keys)
        {
            var weight = serverWeightMap[key];
            for(var i = 0; i < weight; i++)
                ipList.Add(key);
        }
    
        var randPos = Convert.ToInt32((new Random()).Next(ipList.Count));
        var ip = ipList[randPos];
    
        return ip;
    }
    

      上面的两个方法中, 就处理服务器 IP 地址的时候, 根据权重的不同, 在 IP  列表中重复添加 IP 值,权重越大, IP 列表中 IP 值的重复数就越多。

  • 相关阅读:
    【题解】 P1373 小a和uim之大逃离
    题解 CF576C 【Points on Plane】
    题解 P4799 【[CEOI2015 Day2]世界冰球锦标赛】
    【题解】[JSOI2008]最大数
    题解 P3389 【【模板】高斯消元法】
    【模板】矩阵加速
    【模板】树状数组上的差分数组
    tarjan求强连通分量(模板)
    我好菜系列——map查找
    trie树的应用;
  • 原文地址:https://www.cnblogs.com/kuku/p/8463652.html
Copyright © 2011-2022 走看看