golang 哈希负载均衡
代码记录
#package main
import (
“fmt”
“hash/crc32”
“day1/example3/balance”
“math/rand”
)
type HashBalance struct {
}
func init() {
balance.RegisterBalancer(“hash”, &HashBalance{})
}
func (p *HashBalance) DoBalance(insts []*balance.Instance, key…string) (inst *balance.Instance, err error) {
var defKey string = fmt.Sprintf("%d", rand.Int())
if(len(key) > 0) {
//err = fmt.Errorf("hash balance must pass hash key")
defKey = key[0]
}
lens := len(insts)
if(lens ==0) {
err = fmt.Errorf("No backend instance")
return
}
crcTable := crc32.MakeTable(crc32.IEEE)
hasVal := crc32.Checksum([]byte(defKey), crcTable)
index := int(hasVal) % lens
inst = insts[index]
return
}