惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
云风的 BLOG
云风的 BLOG
小众软件
小众软件
V
V2EX
博客园 - Franky
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
量子位
博客园 - 【当耐特】
雷峰网
雷峰网
WordPress大学
WordPress大学
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
N
Netflix TechBlog - Medium
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
V
Visual Studio Blog
Microsoft Security Blog
Microsoft Security Blog

博客园 - 匡匡

Vue 父子组件通信方式 Vue: 组件扩展 WebClient 指定出口 IP IIS8 下 JS, CSS 等静态文件出现 500 错误 使用 ffmpeg 转换 mov 视频 使用 ildasm 和 ilasm 修改程序集的的引用信息 2020-01-08 工作日记:无题 .Net Core 程序集管理说明(加载) .NET CORE 动态加载 DLL 的问题 ASP.NET 后台 COOKIE 的设置 使用 sql server 默认跟踪分析执行的 SQL 语句 Nginx深入详解之upstream分配方式 使用 HttpWebRequest 类做 POST 请求没有应反 webpack 里的 import, exports 实现原理 使用 pdf.js 查看发票时,显示不了台头和印章的解决办法 Flex 布局里 input 宽度最小 150px 的问题, 浏览器 BUG? 使用像素单位设置 EXCEL 列宽或行高 sweetalert 快速显示两个提示, 第二个显示不出的问题 在 Docker 中部署 ASP.NET CORE 应用
加权轮询和加权随机算法
匡匡 · 2018-02-23 · via 博客园 - 匡匡

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

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 值的重复数就越多。