dubbo-go中randomLoadBalance的作用是什么

发布时间:2021-06-22 15:37:19 作者:Leah
来源:亿速云 阅读:153

这期内容当中小编将会给大家带来有关dubbo-go中randomLoadBalance的作用是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

randomLoadBalance

dubbo-go-v1.4.2/cluster/loadbalance/random.go

const (
	name = "random"
)

func init() {
	extension.SetLoadbalance(name, NewRandomLoadBalance)
}

type randomLoadBalance struct {
}

// NewRandomLoadBalance ...
func NewRandomLoadBalance() cluster.LoadBalance {
	return &randomLoadBalance{}
}

Select

dubbo-go-v1.4.2/cluster/loadbalance/random.go

func (lb *randomLoadBalance) Select(invokers []protocol.Invoker, invocation protocol.Invocation) protocol.Invoker {
	var length int
	if length = len(invokers); length == 1 {
		return invokers[0]
	}
	sameWeight := true
	weights := make([]int64, length)

	firstWeight := GetWeight(invokers[0], invocation)
	totalWeight := firstWeight
	weights[0] = firstWeight

	for i := 1; i < length; i++ {
		weight := GetWeight(invokers[i], invocation)
		weights[i] = weight

		totalWeight += weight
		if sameWeight && weight != firstWeight {
			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.
		offset := rand.Int63n(totalWeight)

		for i := 0; i < length; i++ {
			offset -= weights[i]
			if offset < 0 {
				return invokers[i]
			}
		}
	}
	// If all invokers have the same weight value or totalWeight=0, return evenly.
	return invokers[rand.Intn(length)]
}

小结

randomLoadBalance的NewRandomLoadBalance方法创建randomLoadBalance;其Select方法使用了带weight的方法,具体就是使用rand.Int63n(totalWeight)随机一个offset,之后遍历weights,用offset挨个去减weights[i],若offset小于0,则返回invokers[i]

上述就是小编为大家分享的dubbo-go中randomLoadBalance的作用是什么了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. dubbo-go 中的 TPS Limit 设计与实现
  2. javascript中this的作用是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

dubbo-go

上一篇:前端如何使用pdfmake生成现有报告

下一篇:CentOS7系统如何安装极点五笔输入法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》