关于dubbo:聊聊dubbogo的ConsistentHashLoadBalance

36次阅读

共计 4146 个字符,预计需要花费 11 分钟才能阅读完成。

本文次要钻研一下 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{}
}
  • ConsistentHashLoadBalance 的 init 办法设置了名为 consistenthash 的 ConsistentHashLoadBalance 到 extension 中

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)
}
  • Select 办法遍历 invokers 挨个执行 json.Marshal(invoker),将 bytes[] 增加到 bs 中,之后通过 crc32.ChecksumIEEE(bs) 计算 hashCode,而后比照 selectors[key] 的 hashCode 与计算出来的 hashCode 是否统一,不统一则通过 newConsistentHashSelector 从新设置一个,最初执行 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}
  • ConsistentHashSelector 定义了 hashCode、replicaNum、virtualInvokers、keys、argumentIndex 属性

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
}
  • newConsistentHashSelector 办法实例化 ConsistentHashSelector,并初始化 virtualInvokers、hashCode、argumentIndex、keys、virtualInvokers 属性

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
}
  • Select 办法通过 c.toKey(invocation.Arguments()) 获取 key,再通过 md5.Sum([]byte(key)) 计算 digest,最初通过 c.selectForKey(c.hash(digest, 0)) 选取 Invoker

小结

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

doc

  • consistent_hash

正文完
 0