资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

dubbo-go中randomLoadBalance的作用是什么

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

我们提供的服务有:成都网站建设、成都网站设计、微信公众号开发、网站优化、网站认证、靖西ssl等。为数千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的靖西网站制作公司

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{}
}
  • randomLoadBalance的NewRandomLoadBalance方法创建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)]
}
  • Select方法先判断invokers数量,若只有一个则返回invokers[0];之后遍历invokers计算totalWeight及sameWeight,若totalWeight大于0且sameWeight为false则使用rand.Int63n(totalWeight)随机一个offset,之后遍历weights,用offset挨个去减weights[i],若offset小于0,则返回invokers[i];若都没有选中,则返回invokers[rand.Intn(length)]

小结

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

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


本文名称:dubbo-go中randomLoadBalance的作用是什么
网页地址:http://cdkjz.cn/article/ghhjcs.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220