今天用go实现一个简单的负载均衡的算法,虽然简单,还是要写一下。
1.首先就是服务器的信息,
package balance
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
}
2.接着定义接口
package balance
type Balance interface {
/**
*负载均衡算法
*/
DoBalance([] *Instance,...string) (*Instance,error)
}
3.接着,是实现接口,random.go
package balance
import (
"errors"
"math/rand"
)
func init() {
RegisterBalance("random",&RandomBalance{})
}
type RandomBalance struct {
}
func (p *RandomBalance) DoBalance(insts [] *Instance,key...string) (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
}
roundrobin.go
package balance
import (
"errors"
)
func init() {
RegisterBalance("round", &RoundRobinBalance{})
}
type RoundRobinBalance struct {
curIndex int
}
func (p *RoundRobinBalance) DoBalance(insts [] *Instance, key ...string) (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++
return
}
4 然后,全部交给管理器来管理,这也是为什么上面的文件全部重写了init函数
package balance
import (
"fmt"
)
type BalanceMgr struct {
allBalance map[string]Balance
}
var mgr = BalanceMgr{
allBalance: make(map[string]Balance),
}
func (p *BalanceMgr) registerBalance(name string, b Balance) {
p.allBalance[name] = b
}
func RegisterBalance(name string, b Balance) {
mgr.registerBalance(name, b)
}
func DoBalance(name string, insts []*Instance) (inst *Instance, err error) {
balance, ok := mgr.allBalance[name]
if !ok {
err = fmt.Errorf("not fount %s", name)
fmt.Println("not found ",name)
return
}
inst, err = balance.DoBalance(insts)
if err != nil {
err = fmt.Errorf(" %s erros", name)
return
}
return
}
下面进行测试:
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))
port, _ := strconv.Atoi(fmt.Sprintf("880%d", i))
one := balance.NewInstance(host, port)
insts = append(insts, one)
}
var name = "round"
if len(os.Args) > 1 {
name = os.Args[1]
}
for {
inst, err := balance.DoBalance(name, insts)
if err != nil {
fmt.Println("do balance err")
time.Sleep(time.Second)
continue
}
fmt.Println(inst)
time.Sleep(time.Second)
}
}
5.如果想扩展这个,又不入侵原来的代码结构,可以类比上面实现dobalance接口即可
package add
import (
"awesomeProject/test/balance"
"fmt"
"math/rand"
"hash/crc32"
)
func init() {
balance.RegisterBalance("hash", &HashBalance{})
}
type HashBalance struct {
key string
}
func (p *HashBalance) DoBalance(insts [] *balance.Instance, key ...string) (inst *balance.Instance, err error) {
defKey := fmt.Sprintf("%d", rand.Int())
if len(key) > 0 {
defKey = key[0]
}
lens := len(insts)
if lens == 0 {
err = fmt.Errorf("no balance")
return
}
hashVal := crc32.Checksum([]byte(defKey), crc32.MakeTable(crc32.IEEE))
index := int(hashVal) % lens
inst = insts[index]
return
}
这样就能交给管理器统一管理了,而且不会影响原来的api。