一致性哈希

一致性哈希

传统哈希取模在扩容缩容时需要rehash,绝大多数key都需要重新分配,影响很大。因此引入一致性哈希

一致性哈希原理就是一个圆,圆上有节点和虚拟节点,虚拟节点越多,园瓜分的越均匀。然后key对整个圆取模,落到那个节点的范围就属于哪个节点。扩容缩容只会影响到相邻节点的元素。大大降低了影响面
在这里插入图片描述

go语言实现

package consistent_hash_code

import (
	"errors"
	"fmt"
	"hash/crc32"
	"sort"
)

type Consistent struct {
	nodesReplicas int               //添加虚拟节点数量
	hashSortNodes []uint32          //所有节点的排序数组
	circle        map[uint32]string //所有节点对应的node
	nodes         map[string]bool   //node是否存在
}

func NewConsistent(nodesReplicas int) *Consistent {
	return &Consistent{
		nodesReplicas: nodesReplicas,
		circle:        make(map[uint32]string),
		nodes:         make(map[string]bool),
	}
}

func (c *Consistent) Add(node string) error {
	if _, ok := c.nodes[node]; ok { //判断新加节点是否存在
		return fmt.Errorf("%s already existed", node)
	}
	c.nodes[node] = true
	for i := 0; i < c.nodesReplicas; i++ { //添加虚拟节点
		replicasKey := getReplicasKey(i, node) //虚拟节点
		c.circle[replicasKey] = node
		c.hashSortNodes = append(c.hashSortNodes, replicasKey) //所有节点ID
	}
	sort.Slice(c.hashSortNodes, func(i, j int) bool { //排序
		return c.hashSortNodes[i] < c.hashSortNodes[j]
	})
	return nil
}

func (c *Consistent) Remove(node string) error {
	if _, ok := c.nodes[node]; !ok { //判断新加节点是否存在
		return fmt.Errorf("%s not existed", node)
	}
	delete(c.nodes, node)
	for i := 0; i < c.nodesReplicas; i++ {
		replicasKey := getReplicasKey(i, node)
		delete(c.circle, replicasKey) //删除虚拟节点
	}
	c.refreshHashSortNodes()
	return nil
}
func (c *Consistent) GetNode() (node []string) {
	for v := range c.nodes {
		node = append(node, v)
	}
	return node
}

func (c *Consistent) Get(key string) (string, error) {
	if len(c.nodes) == 0 {
		return "", errors.New("not add node")
	}
	index := c.searchNearbyIndex(key)
	host := c.circle[c.hashSortNodes[index]]
	return host, nil
}

func (c *Consistent) refreshHashSortNodes() {
	c.hashSortNodes = nil
	for v := range c.circle {
		c.hashSortNodes = append(c.hashSortNodes, v)
	}
	sort.Slice(c.hashSortNodes, func(i, j int) bool { //排序
		return c.hashSortNodes[i] < c.hashSortNodes[j]
	})
}

func (c *Consistent) searchNearbyIndex(key string) int {
	hashKey := hashKey(key)
	index := sort.Search(len(c.hashSortNodes), func(i int) bool { //key算出的节点,距离最近的node节点下标  sort.Search数组需要升序排列好
		return c.hashSortNodes[i] >= hashKey
	})
	if index >= len(c.hashSortNodes) {
		index = 0
	}
	return index
}

func getReplicasKey(i int, node string) uint32 {
	return hashKey(fmt.Sprintf("%s#%d", node, i))
}

func hashKey(host string) uint32 {
	return crc32.ChecksumIEEE([]byte(host))
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值