基于hash算法的分流思想

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyaya8/article/details/88015355

前言

在互联网的时代,负载均衡以及机房,集群的容灾是必不可少的,这些功能的背后是软件和硬件的配合达到的效果,之前在公司实习的时候涉及到相关的分流算法,写此记录下来

背景

有两个集群A,B。A为主用机房,当A挂掉或者流量过大,可以将全部流量或者部分流量切换到B机房上,来提高服务的可用性,因为这个服务比较核心,是RPC应用,所以我决定在请求底层接口上对其应用算法

代码实现

对整型id的分流处理
func queryUserByIntId(userId int) bool {
	//从配置中心获取配置文件,此处代码实现逻辑就不写了
	list := GetConf()
	userId = hashInt(userId)
	if list.contain(userId) {
		return true
	}
	return false
}
//对字符串的id分流处理
func queryUserByStrId(userId string) bool {
	//从配置中心获取配置文件,此处代码实现逻辑就不写了
	list := GetConf()
	id := hashString(userId)
	if list.contain(id) {
		return true
	}
	return false
}

type Collection []int

func (collection Collection) contain(a int) bool {
	for value := range collection {
		if value == a {
			return true
		}
	}
	return false
}
//对值进行hash处理,粒度为15
func hashInt(value int) (hashValue int) {
	return value & 15
}

//此处是伪配置,应该从配置中心动态获取开关
//根据配置的切片可可以定义0-7的时候是A,B机房各一半流量,
//全部0-15是全部走B机房,不写走A机房
func GetConf() Collection {
	return []int{0, 1, 2, 3, 4, 5, 6, 7,}
}

//对字符串进行hash
func hashString(value string) (hashValue int) {
	b := []byte(value)[0]
	return hashInt(int(b))
}

猜你喜欢

转载自blog.csdn.net/tangyaya8/article/details/88015355