基于轮询和随机的负载均衡算法实现方式
package main
import (
"errors"
"fmt"
"math"
"math/rand"
"sync"
"time"
)
type MultiServersDiscovery struct{
r *rand.Rand
mu sync.RWMutex
servers []string
index int
mode string
}
func NewMultiServersDiscovery(servers []string) *MultiServersDiscovery{
d := &MultiServersDiscovery{
servers: servers,
r: rand.New(rand.NewSource(time.Now().Unix())),
}
d.index = rand.Intn(math.MaxInt32-1)
return d
}
func (d *MultiServersDiscovery)Get(mode string)(string, error){
d.mu.Lock()
defer d.mu.Unlock()
n := len(d.servers)
switch mode{
//基于轮询
case "roundrobin":
server := d.servers[d.index%n]
d.index = (d.index+1)%n
return server, nil
//基于随机
case "random":
server := d.servers[rand.Intn(n)]
return server, nil
}
return "", errors.New("service not found")
}
func main(){
services := []string{"srv1","srv2","srv3","srv4"}
multiDiscovery := NewMultiServersDiscovery(services)
for i:=0;i<10;i++{
server, err := multiDiscovery.Get("random")
if err != nil {
fmt.Println("err: ",err)
}
fmt.Print(server+" ")
}
}