Golang之实现一个负载均衡算法(随机,轮询)
生活随笔
收集整理的這篇文章主要介紹了
Golang之实现一个负载均衡算法(随机,轮询)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼記錄
程序結(jié)構(gòu)目錄
--------程序包
balance.go
package balancetype Balancer interface {DoBalance([]*Instance, ...string) (*Instance, error) }instance.go
package balanceimport ("strconv" )type Instance struct {host stringport int }func NewInstance(host string, port int) *Instance {return &Instance{host: host,port: port,} }//定義Instance結(jié)構(gòu)體的方法GetHost() func (p *Instance) GetHost() string {return p.host }//定義方法GetPort() func (p *Instance) GetPort() int {return p.port } func (p *Instance) String() string {return p.host + ":" + strconv.Itoa(p.port) }mgr.go
package balanceimport "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 balancer", name)return}fmt.Printf("use %s balancer\n", name)inst, err = balancer.DoBalance(insts)return }random.go
package balanceimport ("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 instance")return}lens := len(insts)index := rand.Intn(lens)inst = insts[index]return }roundrobin.go
package balanceimport ("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 instance")return}lens := len(insts)if p.curIndex >= lens {p.curIndex = 0}inst = insts[p.curIndex]p.curIndex = (p.curIndex + 1) % lensreturn }------入口
main.go
package mainimport ("fmt""../balance""math/rand""os""time" )func main() {var insts []*balance.Instancefor 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("do balance err:", err)fmt.Fprintf(os.Stdout, "do balance err\n")continue}fmt.Println(inst)time.Sleep(time.Second)} }hash.go
package mainimport ("fmt""../balance""hash/crc32""math/rand" )type HashBalance struct {Name stringAge int }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[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) % lensinst = insts[index]return }總結(jié)
以上是生活随笔為你收集整理的Golang之实现一个负载均衡算法(随机,轮询)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux tree命令以树形结构显示文
- 下一篇: 树莓派命令行模式调整音量