负载均衡粗略

package balance

typeBalancerinterface{
    DoBalance([]*Instance) (*Instance,error)
}
package balance
import(
    "strconv"
)
type Instance struct{
    host string
    port int
}

func NewInstance(host string,port int)*Instance {
    return &Instance{
        host:host,
        port:port,
    }
}
func (p *Instance)Gethost()string{
    return p.host
}
func (p *Instance)Getport()int{
    return p.port
}
func (p *Instance)String()string{
    return p.host+":"+strconv.Itoa(p.port)
}
package balance

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)
}
package balance
import(
    "errors"
    "math/rand"
)
type RandomBalance struct{
}
func init(){
    RegisterBalancer("random",&RandomBalance{})
}
func (p *RandomBalance)DoBalance(insts []*Instance)(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
}
package balance
import(
    "errors"
)
type RoundRobinBalance struct{
    curIndex int
}
func (p *RoundRobinBalance)DoBalance(insts []*Instance)(inst *Instance,err error){
    if len(insts)==0{
        err=errors.New("no instance")
        return
    }
    lens:=len(insts)
    inst=insts[p.curIndex]
    p.curIndex=(p.curIndex+1)%lens
    return
}

 

posted @ 2019-06-17 15:41  RedFace  阅读(105)  评论(0)    收藏  举报