博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Dubbo中基于权重的随机算法
阅读量:6866 次
发布时间:2019-06-26

本文共 1909 字,大约阅读时间需要 6 分钟。

转载自

dubbo的源码地址:

Dubbo中的RandomLoadBalance采用基于权重的随机算法,主要代码如下:

public class RandomLoadBalance extends AbstractLoadBalance {    public static final String NAME = "random";    private final Random random = new Random();    protected 
Invoker
doSelect(List
> invokers, URL url, Invocation invocation) { int length = invokers.size(); // Number of invokers int totalWeight = 0; // The sum of weights boolean sameWeight = true; // Every invoker has the same weight? for (int i = 0; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); totalWeight += weight; // Sum if (sameWeight && i > 0 && weight != getWeight(invokers.get(i - 1), invocation)) { sameWeight = false; } } if (totalWeight > 0 && !sameWeight) { // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight. int offset = random.nextInt(totalWeight); // Return a invoker based on the random value. for (int i = 0; i < length; i++) { offset -= getWeight(invokers.get(i), invocation); if (offset < 0) { return invokers.get(i); } } } // If all invokers have the same weight value or totalWeight=0, return evenly. return invokers.get(random.nextInt(length)); }}

解说:

数学分析

1)假设有四个集群节点A,B,C,D,对应的权重分别是1,2,3,4,那么请求到A节点的概率就为1/(1+2+3+4) = 10%.B,C,D节点依次类推为20%,30%,40%.

2)虽然这个随机算法理解起来是比较容易的,面试一般不会问这个,但是假如我们要实现类似的功能,他这个代码实现的思路还是很优雅的,非常具有借鉴意义.他这个实现思路从纯数学角度是很好理解的,我们还是按照上面数学分析中的前提条件.我们知道总权重为10(1+2+3+4),那么怎么做到按权重随机呢?根据10随机出一个整数,假如为随机出来的是2.然后依次和权重相减,比如2(随机数)-1(A的权重) = 1,然后1(上一步计算的结果)-2(B的权重) = -1,此时-1 < 0,那么则调用B,其他的以此类推

转载于:https://blog.51cto.com/woodpecker/2071045

你可能感兴趣的文章
前端使用fis3开启本地服务器,并实现热加载功能
查看>>
看BAT技术面试官如何挑选Java程序员
查看>>
AI强势来袭,锁上手机就真的安全了吗?
查看>>
Spring 中的 context
查看>>
重构代码(应如写诗)
查看>>
Vue混入mixins
查看>>
前阿里 P9 级员工称离婚是模拟测试,已回滚复婚!
查看>>
衡阳a货翡翠,南平a货翡翠
查看>>
大姨太入场,EtcGame全线升级为Coingame,开启ETH投注倒计时……
查看>>
阿里云HBase推出全新X-Pack服务 定义HBase云服务新标准
查看>>
通过Auto Layout深入了解SizeClasses的好处和使用
查看>>
Spring scope解惑
查看>>
BCH与BCE共享比特币之名
查看>>
js脚本 处理js注入
查看>>
A potentially dangerous Request.Form value was detected from the client
查看>>
测试过程之过分关注功能性测试
查看>>
SQL Server -- LIKE模糊查询
查看>>
centos7.0 docker安装部署
查看>>
ORA-32004错误的解决方法
查看>>
嵌入式系统学习步骤
查看>>