Golang之實現一個負載平衡演算法(隨機,輪詢)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

代碼記錄

程式結構目錄

--------程式包

package balancetype Balancer interface {    DoBalance([]*Instance, ...string) (*Instance, error)}
balance.go
package balanceimport (    "strconv")type Instance struct {    host string    port int}func NewInstance(host string, port int) *Instance {    return &Instance{        host: host,        port: port,    }}//定義Instance結構體的方法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)}
instance.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}
mgr.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}
random.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) % lens    return}
roundrobin.go

------入口

package mainimport (    "fmt"    "go_dev/day7/example/example1/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("do balance err:", err)            fmt.Fprintf(os.Stdout, "do balance err\n")            continue        }        fmt.Println(inst)        time.Sleep(time.Second)    }}
main.go
package mainimport (    "fmt"    "go_dev/day7/example/example1/balance"    "hash/crc32"    "math/rand")type HashBalance struct {    Name string    Age  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) % lens    inst = insts[index]    return}
hash.go

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.