package util type HttpServer struct { Host string Weight int } type LoadBalance struct { Server []*HttpServer CurrentIndex int } var MapWeight []int func NewHttpServe(host string, weight int) *HttpServer{ return &HttpServer{Host: host,Weight: weight} } func NewBalance() *LoadBalance { return &LoadBalance{Server: make([]*HttpServer,0)} } func (this *LoadBalance) AddServer(server *HttpServer){ this.Server = append(this.Server,server) }
调用方
package main func main() { //lib:= util.NewBalance() //newHttp1:=util.NewHttpServe("http://localhost:9091",5) //newHttp2:=util.NewHttpServe("http://localhost:9092",7) //newHttp3:=util.NewHttpServe("http://localhost:9092",10) //newHttp4:=util.NewHttpServe("http://localhost:9092",20) //lib.AddServer(newHttp1) //lib.AddServer(newHttp2) //lib.AddServer(newHttp3) //lib.AddServer(newHttp4) }
1。各种基础模拟
//随机算法随机一个ip地址 //func (this * LoadBalance) RandromIpSoft() int { // ipNum:=len(this.Server) // rand.Seed(time.Now().UnixNano()) // index:=rand.Intn(ipNum) // return index //} //iphash算法 //func (this *LoadBalance) RandromIpSoft(ip string ) uint32 { // ipNum := crc32.ChecksumIEEE([]byte(ip)) // index:= ipNum%uint32(len(this.Server)) // return index //} //加权算法 //func (this *LoadBalance) RandromIpSoft() []int { // for k,val:=range this.Server { // for i:=0;i<val.Weight;i++ { // MapWeight = append(MapWeight,k) // } // } // return MapWeight //} //加权算法改良版 //func (this *LoadBalance) RandromIpSoft() *HttpServer { // var mapList []int // sum:=0 // for _,val:=range this.Server { // sum+=val.Weight // mapList=append(mapList,sum) // } // rand.Seed(time.Now().UnixNano()) // rad:= rand.Intn(sum) // for index,val:=range mapList{ // if rad < val { // return this.Server[index] // } // } // return this.Server[0] //} //轮询 //func (this * LoadBalance)RoundFrom() int { // index:= (this.CurrentIndex+1)%len(this.Server) // return index //} //加权轮训 //func Lunxun(){ // arrWeight:=[]int{3,1,1} // sliceNode:=make([]int,0) // // for k,v:=range arrWeight{ // for i:=0; i<v;i++ { // sliceNode= append(sliceNode,k) // } // } // CurrIndex:=0 // var point int // for CurrIndex < 10 { // if point >=len(sliceNode) { // point=0 // } // log.Println(sliceNode[point]) // point+=1 // time.Sleep(1* time.Second) // CurrIndex+=1 // } //}
标签:HttpServer,int,LoadBalance,Server,util,算法,反向,func,go From: https://www.cnblogs.com/zh718594493/p/16909833.html