实现基本的平均负载均衡

This commit is contained in:
suguo.yao 2021-01-23 22:15:31 +08:00
parent ceb0903819
commit a9ce2c9a82
2 changed files with 14 additions and 3 deletions

View File

@ -19,6 +19,9 @@ func main() {
}).Errorf("%v", err)
return
}
if node == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// conn, err := grpc.Dial("127.0.0.1:9001", grpc.WithBlock(), grpc.WithInsecure())

View File

@ -2,6 +2,8 @@ package consul
import (
"fmt"
"math/rand"
"time"
consulapi "github.com/hashicorp/consul/api"
log "github.com/sirupsen/logrus"
@ -78,10 +80,16 @@ func FindNode(servicename string) (*consulapi.AgentService, error) {
if err != nil {
return nil, err
}
for _, service := range services {
return service.Service, nil
l := len(services)
if l == 0 {
return nil, nil
}
return nil, nil
if l == 1 {
return services[0].Service, nil
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return services[r.Intn(l)%l].Service, nil
}
//FindServer 从consul中发现服务