1疮蹦、接口(輪訓(xùn)和隨機(jī)調(diào)度兩個(gè)接口)
balance.go
package balance
//調(diào)用那種輪訓(xùn)方式接口
type Balancer interface {
DoBalance([]*Instance) (*Instance, error)
}
2黔牵、定義主機(jī)列表
instance.go
package balance
//主機(jī)列表
type Instance struct {
host string
port int
}
// 因?yàn)樯厦鏋樾戦_頭不支持外部訪問吁系,下面為封裝后外部可直接調(diào)用
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
}
3韭畸、隨機(jī)調(diào)度
random.go
package balance
import (
"errors"
"math/rand"
)
//初始化,調(diào)用此文件輪訓(xùn)方式為隨機(jī)
func init() {
RegisterBalancer("random", &RandomBalance{})
}
type RandomBalance struct {
}
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
}
4伸头、輪訓(xùn)調(diào)度
roudrobin.go
package balance
import "errors"
func init() {
RegisterBalancer("roundrobin", &RoundRobinBalance{})
}
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)
if p.curIndex >= lens {
p.curIndex = 0
}
inst = insts[p.curIndex]
p.curIndex = (p.curIndex + 1) % lens
return
}
5匾效、管理文件
mgr.go
package balance
import (
"fmt"
)
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)
}
func DoBalance(name string, insts []*Instance) (inst *Instance, err error) {
balancer, ok := mgr.allBalancer[name]
if !ok {
err = fmt.Errorf("Not found %s balancer", name)
return
}
fmt.Printf("use %s balance\n", name)
inst, err = balancer.DoBalance(insts)
return
}
6、入口函數(shù)
main.go
package main
import (
"fmt"
"go_dev/day7/example3/balance"
"math/rand"
"os"
"time"
)
func main() {
var insts []*balance.Instance
for i := 0; i < 10; i++ {
host := fmt.Sprintf("192.168.%d.%d", rand.Intn(255), rand.Intn(255))
one := balance.NewInstance(host, 8080)
insts = append(insts, one)
}
var balanceName = "random"
if len(os.Args) > 1 {
balanceName = os.Args[1]
}
for {
inst, err := balance.DoBalance(balanceName, insts)
if err != nil {
fmt.Println("do balance err:", err)
continue
}
fmt.Println(inst)
time.Sleep(time.Second)
}
}