步骤
1、创建节点信息
2、为节点创建虚拟节点
3、根据虚拟节点的hashKey排序
4、根据提供的key信息,进行hash计算,查找匹配的节点
代码
package main
import (
"crypto/md5"
"crypto/rand"
"fmt"
"hash/crc32"
"sort"
"sync"
"sync/atomic"
"time"
)
type Node struct {
Id int
Info string
Count int32
}
type ConsistentHash struct {
mutex sync.RWMutex
nodes map[uint32]*Node //[hash key] => node
replicas int //每个节点的虚拟节点数
sk []uint32 //保存排序好的hash环上的key
}
func (ch *ConsistentHash) Add(node *Node) { //增加节点
ch.mutex.RLock()
defer ch.mutex.RUnlock()
for i := 0; i < ch.replicas; i++ {
hashNum := geth