dubbo-go中ConsistentHashLoadBalance的用法

发布时间:2021-07-09 18:03:06 作者:chen
来源:亿速云 阅读:114

本篇内容介绍了“dubbo-go中ConsistentHashLoadBalance的用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

本文主要研究一下dubbo-go的ConsistentHashLoadBalance

ConsistentHashLoadBalance

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

const (
	// ConsistentHash ...
	ConsistentHash = "consistenthash"
	// HashNodes ...
	HashNodes = "hash.nodes"
	// HashArguments ...
	HashArguments = "hash.arguments"
)

var (
	selectors = make(map[string]*ConsistentHashSelector)
	re        = regexp.MustCompile(constant.COMMA_SPLIT_PATTERN)
)

func init() {
	extension.SetLoadbalance(ConsistentHash, NewConsistentHashLoadBalance)
}

// ConsistentHashLoadBalance ...
type ConsistentHashLoadBalance struct {
}

// NewConsistentHashLoadBalance ...
func NewConsistentHashLoadBalance() cluster.LoadBalance {
	return &ConsistentHashLoadBalance{}
}

Select

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

// Select ...
func (lb *ConsistentHashLoadBalance) Select(invokers []protocol.Invoker, invocation protocol.Invocation) protocol.Invoker {
	methodName := invocation.MethodName()
	key := invokers[0].GetUrl().ServiceKey() + "." + methodName

	// hash the invokers
	bs := make([]byte, 0)
	for _, invoker := range invokers {
		b, err := json.Marshal(invoker)
		if err != nil {
			return nil
		}
		bs = append(bs, b...)
	}
	hashCode := crc32.ChecksumIEEE(bs)
	selector, ok := selectors[key]
	if !ok || selector.hashCode != hashCode {
		selectors[key] = newConsistentHashSelector(invokers, methodName, hashCode)
		selector = selectors[key]
	}
	return selector.Select(invocation)
}

ConsistentHashSelector

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

// ConsistentHashSelector ...
type ConsistentHashSelector struct {
	hashCode        uint32
	replicaNum      int
	virtualInvokers map[uint32]protocol.Invoker
	keys            Uint32Slice
	argumentIndex   []int
}

newConsistentHashSelector

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

func newConsistentHashSelector(invokers []protocol.Invoker, methodName string,
	hashCode uint32) *ConsistentHashSelector {

	selector := &ConsistentHashSelector{}
	selector.virtualInvokers = make(map[uint32]protocol.Invoker)
	selector.hashCode = hashCode
	url := invokers[0].GetUrl()
	selector.replicaNum = int(url.GetMethodParamInt(methodName, HashNodes, 160))
	indices := re.Split(url.GetMethodParam(methodName, HashArguments, "0"), -1)
	for _, index := range indices {
		i, err := strconv.Atoi(index)
		if err != nil {
			return nil
		}
		selector.argumentIndex = append(selector.argumentIndex, i)
	}
	for _, invoker := range invokers {
		u := invoker.GetUrl()
		address := u.Ip + ":" + u.Port
		for i := 0; i < selector.replicaNum/4; i++ {
			digest := md5.Sum([]byte(address + strconv.Itoa(i)))
			for j := 0; j < 4; j++ {
				key := selector.hash(digest, j)
				selector.keys = append(selector.keys, key)
				selector.virtualInvokers[key] = invoker
			}
		}
	}
	sort.Sort(selector.keys)
	return selector
}

Select

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

// Select ...
func (c *ConsistentHashSelector) Select(invocation protocol.Invocation) protocol.Invoker {
	key := c.toKey(invocation.Arguments())
	digest := md5.Sum([]byte(key))
	return c.selectForKey(c.hash(digest, 0))
}

func (c *ConsistentHashSelector) toKey(args []interface{}) string {
	var sb strings.Builder
	for i := range c.argumentIndex {
		if i >= 0 && i < len(args) {
			fmt.Fprint(&sb, args[i].(string))
		}
	}
	return sb.String()
}

func (c *ConsistentHashSelector) selectForKey(hash uint32) protocol.Invoker {
	idx := sort.Search(len(c.keys), func(i int) bool {
		return c.keys[i] >= hash
	})
	if idx == len(c.keys) {
		idx = 0
	}
	return c.virtualInvokers[c.keys[idx]]
}

func (c *ConsistentHashSelector) hash(digest [16]byte, i int) uint32 {
	return uint32((digest[3+i*4]&0xFF)<<24) | uint32((digest[2+i*4]&0xFF)<<16) |
		uint32((digest[1+i*4]&0xFF)<<8) | uint32(digest[i*4]&0xFF)&0xFFFFFFF
}

小结

ConsistentHashLoadBalance的Select方法遍历invokers挨个执行json.Marshal(invoker),将bytes[]添加到bs中,之后通过crc32.ChecksumIEEE(bs)计算hashCode,然后对比selectors[key]的hashCode与计算出来的hashCode是否一致,不一致则通过newConsistentHashSelector重新设置一个,最后执行selector.Select(invocation)

“dubbo-go中ConsistentHashLoadBalance的用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. Python中“_”的用法
  2. JavaScript中this的用法

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

dubbo

上一篇:什么是Python运算符重载

下一篇:sharding-jdbc中SQLExecutionHook的用法

相关阅读

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

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