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])]
}

 

posted @ 2018-01-25 14:28  孤独的和弦  阅读(304)  评论(0编辑  收藏  举报