开心123 发表于 2018-9-20 12:52:43

Golang之实现一个负载均衡算法(随机,轮询)

package main  

  
import (
  

"fmt"  
"go_dev/day7/example/example1/balance"
  
"hash/crc32"
  
"math/rand"
  
)
  

  
type HashBalance struct {
  
Name string
  
Ageint
  
}
  

  
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 {
  
defKey = key
  
}
  
lens := len(insts)
  
if lens == 0 {
  
err = fmt.Errorf("No backend instance")
  
return
  
}
  
crcTable := crc32.MakeTable(crc32.IEEE)
  
hashVal := crc32.Checksum([]byte(defKey), crcTable)
  
index := int(hashVal) % lens
  
inst = insts
  
return
  
}


页: [1]
查看完整版本: Golang之实现一个负载均衡算法(随机,轮询)