实现一个负载均衡调度算法,支持随机、轮询等算法(新手)

LeeHung · · 630 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

https://github.com/Hung-Lee/Balance 一、定义接口 ```go package balance type Balancer interface { DoBalance([]*Instance, ...string) (*Instance, error) } ``` 二、定义IP端口结构体 ```go package balance import "strconv" type Instance struct { host string port int } func NewInstance(host string, port int) *Instance { return &Instance{ host: host, port: port, } } func (p *Instance) GetHost() string { return p.host } func (p *Instance) GetPort() int { return p.port } func (p *Instance) String() string { return p.host + ":" + strconv.Itoa(p.port) } ``` 三、注册 ```go package balance import "fmt" type BalanceMgr struct { allBalancer map[string]Balancer } var mgr = BalanceMgr{ allBalancer: make(map[string]Balancer), } func (p *BalanceMgr) registerBalancer(name string, b Balancer) { p.allBalancer[name] = b } func RegisterBalancer(name string, b Balancer) { mgr.registerBalancer(name, b) } func DoBalance(name string, insts []*Instance) (inst *Instance, err error) { balancer, ok := mgr.allBalancer[name] if !ok { err = fmt.Errorf("Not found %s balance", name) return } fmt.Printf("use %s balancer\n", name) inst, err = balancer.DoBalance(insts) return } ``` 四、随机 ```go package balance import ( "errors" "math/rand" ) func init() { RegisterBalancer("random", &RandomBalance{}) } type RandomBalance struct { } func (p *RandomBalance) DoBalance(insts []*Instance, key ...string) (inst *Instance, err error) { if len(insts) == 0 { err = errors.New("No instence") return } lens := len(insts) index := rand.Intn(lens) inst = insts[index] return } ``` 五、轮询 ```go package balance import ( "errors" ) func init() { RegisterBalancer("roundrobin", &RoundRobinBalance{}) } type RoundRobinBalance struct { curIndex int } func (p *RoundRobinBalance) DoBalance(insts []*Instance, key ...string) (inst *Instance, err error) { if len(insts) == 0 { err = errors.New("No instence") return } lens := len(insts) if p.curIndex >= lens { p.curIndex = 0 } inst = insts[p.curIndex] p.curIndex = (p.curIndex + 1) % lens return } ``` 六、hash ```go package balance import ( "fmt" "hash/crc32" "math/rand" ) type HashBalance struct { key string } func init() { RegisterBalancer("hash", &HashBalance{}) } func (p *HashBalance) DoBalance(insts []*Instance, key ...string) (inst *Instance, err error) { var defKey string = fmt.Sprintf("%d", rand.Int()) if len(key) > 0 { defKey = key[0] } 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[index] return } ``` 七、主函数main ```go package main import ( "fmt" "go_dev/balance" "math/rand" "os" "time" ) func main() { var insts []*balance.Instance for i := 0; i < 16; i++ { host := fmt.Sprintf("192.168.%d.%d", rand.Intn(255), rand.Intn(255)) one := balance.NewInstance(host, 8080) insts = append(insts, one) } var balanceName = "random" if len(os.Args) > 1 { balanceName = os.Args[1] } for { inst, err := balance.DoBalance(balanceName, insts) if err != nil { fmt.Println("no balance err", err) continue } fmt.Println(inst) time.Sleep(time.Second) } } ```

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

630 次点击  ∙  1 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传