简单随机算法实现负载均衡

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]
}




相关推荐