简单随机算法实现负载均衡
package util import ( "math/rand" "time" ) type HttpServer struct { //目标server类 Host string } func NewHttpServer(host string) *HttpServer { return &HttpServer{Host: host} } type LoadBalance struct { //负载均衡类 Servers []*HttpServer } func NewLoadBalance() *LoadBalance { return &LoadBalance{Servers: make([]*HttpServer, 0)} } func (this *LoadBalance) AddServer(server *HttpServer) { this.Servers = append(this.Servers, server) } func (this *LoadBalance) SelectForRand() *HttpServer { rand.Seed(time.Now().UnixNano()) index := rand.Intn(len(this.Servers)) return this.Servers[index] } func (this *LoadBalance) SelectByIpHash(ip string) *HttpServer { index := int(crc32.ChecksumIEEE([]byte(ip))) % len(this.Servers) //通过取余永远index都不会大于this.servers的长度 return this.Servers[index] }
相关推荐
Happyunlimited 2020-04-30
troysps 2020-03-04
风吹夏天 2020-01-24
yedaoxiaodi 2020-01-06
魏莉的微 2019-12-19
baike 2019-12-19
shawsun 2019-12-15
baike 2019-12-08
微分 2018-03-02
Qunicy 2019-07-09
郭岚 2019-06-28
YUAN 2019-06-28
ZhuZhuWonder 2019-06-17
MachineIntellect 2015-07-10
蜗牛慢爬的李成广 2019-05-12
StrongHYQ 2018-07-01