golang 实现简单的一致性哈希

Posted 孤独的和弦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 实现简单的一致性哈希相关的知识,希望对你有一定的参考价值。

package main

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

var serverMap  map[uint32]string
var sortedKeys []int

func main() {

    serverMap = make(map[uint32]string)

    var servers []string
    servers = append(servers,"192.168.1.100")
    servers = append(servers,"192.168.1.101")
    servers = append(servers,"192.168.1.102")
    servers = append(servers,"192.168.1.103")
    servers = append(servers,"192.168.1.104")


    for s:=range servers{
        serverMap[hashStr(servers[s])] = servers[s]
    }

    fmt.Println(serverMap)

    for k:=range serverMap{
        sortedKeys = append(sortedKeys,int(k))
    }
    sort.Ints(sortedKeys)

    fmt.Println(sortedKeys)

    obj1:=""
    obj2:=""
    obj3:=""
    obj4:=""
    obj5:=""
    obj6:=""
    obj7:=""

    obj1_key := hashStr(obj1)
    obj2_key := hashStr(obj2)
    obj3_key := hashStr(obj3)
    obj4_key := hashStr(obj4)
    obj5_key := hashStr(obj5)
    obj6_key := hashStr(obj6)
    obj7_key := hashStr(obj7)


    fmt.Println("obj1 ",obj1," hash,",obj1_key," stored at server ",getserver(int(obj1_key)))
    fmt.Println("obj2 ",obj2," hash,",obj2_key," stored at server ",getserver(int(obj2_key)))
    fmt.Println("obj3 ",obj3," hash,",obj3_key," stored at server ",getserver(int(obj3_key)))
    fmt.Println("obj4 ",obj4," hash,",obj4_key," stored at server ",getserver(int(obj4_key)))
    fmt.Println("obj5 ",obj5," hash,",obj5_key," stored at server ",getserver(int(obj5_key)))
    fmt.Println("obj6 ",obj6," hash,",obj6_key," stored at server ",getserver(int(obj6_key)))
    fmt.Println("obj7 ",obj7," hash,",obj7_key," stored at server ",getserver(int(obj7_key)))

}
//  MurMurHash算法
func hashStr(key string) uint32 {
    return crc32.ChecksumIEEE([]byte(key))
}

func getserver(objkey int) string  {

    for _,v:=range sortedKeys{
        if  objkey<v{
            return serverMap[uint32(v)]
        }

    }
    return serverMap[uint32(sortedKeys[0])]
}

 

以上是关于golang 实现简单的一致性哈希的主要内容,如果未能解决你的问题,请参考以下文章

代码片段 - Golang 实现简单的 Web 服务器

架构实践使用 golang 实现一致性Hash算法代码

一致性哈希的golang实现

golang代码片段(摘抄)

分布式系统基石之一(一致性 hash 算法)

一致性哈希算法PHP测试片段