实现基本的平均负载均衡
This commit is contained in:
parent
ceb0903819
commit
a9ce2c9a82
|
|
@ -19,6 +19,9 @@ func main() {
|
||||||
}).Errorf("%v", err)
|
}).Errorf("%v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if node == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
// conn, err := grpc.Dial("127.0.0.1:9001", grpc.WithBlock(), grpc.WithInsecure())
|
// conn, err := grpc.Dial("127.0.0.1:9001", grpc.WithBlock(), grpc.WithInsecure())
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,8 @@ package consul
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"time"
|
||||||
|
|
||||||
consulapi "github.com/hashicorp/consul/api"
|
consulapi "github.com/hashicorp/consul/api"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
|
|
@ -78,10 +80,16 @@ func FindNode(servicename string) (*consulapi.AgentService, error) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, service := range services {
|
l := len(services)
|
||||||
return service.Service, nil
|
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中发现服务
|
//FindServer 从consul中发现服务
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue