golang实现一致性哈希算法

package main


import (
	"crypto/sha1"
	"sync"
	"math"
	"sort"
	"strconv"
	"fmt"
)

const (
	node1 = "192.168.1.1"
	node2 = "192.168.1.2"
	node3 = "192.168.1.3"
)


const (
	//DefaultVirualSpots default virual spots
	DefaultVirualSpots = 400
)

//节点信息
type node struct {
	nodeKey   string    //节点的key
	spotValue uint32  //节点的槽位值
}

type nodesArray []node

func (p nodesArray) Len() int           { return len(p) }
func (p nodesArray) Less(i, j int) bool { return p[i].spotValue < p[j].spotValue }
func (p nodesArray) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p nodesArray) Sort()              { sort.Sort(p) }

//HashRing store nodes and weigths
type HashRing struct {
	virualSpots int   //虚拟节点
	nodes       nodesArray  //节点数组(槽位)
	weights     map[string]int  //节点信息对应其权重
	mu          sync.RWMutex
}

//NewHashRing create a hash ring with virual spots
//初始化Hash环
func NewHashRing() *HashRing {
	spots := DefaultVirualSpots

	h := &HashRing{
		virualS
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值