编程语言
首页 > 编程语言> > 轮询算法

轮询算法

作者:互联网

package util

import (
    "fmt"
    "hash/crc32"
    "math/rand"
    "time"
)

type HttpServer struct { //目标server类
    Host   string
    Weight int
}

func NewHttpServer(host string, weight int) *HttpServer {
    return &HttpServer{Host: host, Weight: weight}
}

type LoadBalance struct { //负载均衡类
    Servers  []*HttpServer
    CurIndex int //指向当前访问的服务器
}

func NewLoadBalance() *LoadBalance {
    return &LoadBalance{Servers: make([]*HttpServer, 0)}
}

func (this *LoadBalance) AddServer(server *HttpServer) {
    this.Servers = append(this.Servers, server)
}

func (this *LoadBalance) RoundRobin() *HttpServer {
    server := this.Servers[this.CurIndex]
    //this.CurIndex++
    //if this.CurIndex >= len(this.Servers) {
    //    this.CurIndex = 0
    //}
    this.CurIndex = (this.CurIndex + 1) % len(this.Servers) //因为一个数的余数永远在0-它本身之间,所以用这种方式得到的轮询更好
    return server
}

var LB *LoadBalance
var ServerIndices []int

func init() {
    LB = NewLoadBalance()
    LB.AddServer(NewHttpServer("http://localhost:8001/web1", 5))  //web1
    LB.AddServer(NewHttpServer("http://localhost:8002/web2", 15)) //web2
    for index, server := range LB.Servers {
        if server.Weight > 0 {
            for i := 0; i < server.Weight; i++ {
                ServerIndices = append(ServerIndices, index)
            }
        }
    }
}


来自为知笔记(Wiz)

标签:HttpServer,LB,轮询,LoadBalance,server,算法,CurIndex,Servers
来源: https://www.cnblogs.com/hualou/p/12070723.html