基本实现服务查找与调用

This commit is contained in:
suguo.yao 2021-01-23 21:58:32 +08:00
parent 16ab9eb14d
commit ceb0903819
3 changed files with 40 additions and 4 deletions

View File

@ -2,6 +2,7 @@ package main
import ( import (
"context" "context"
"fmt"
"time" "time"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -11,10 +12,17 @@ import (
) )
func main() { func main() {
consul.FindServer() node, err := consul.FindNode("demo")
if err != nil {
log.WithFields(log.Fields{
"func": "main",
}).Errorf("%v", err)
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())
// conn, err := grpc.DialContext(ctx, "consul://127.0.0.1:8500/demo", grpc.WithBlock(), grpc.WithInsecure(), grpc.WithBalancerName("round_robin")) conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", node.Address, node.Port), grpc.WithBlock(), grpc.WithInsecure(), grpc.WithBalancerName("round_robin"))
if err != nil { if err != nil {
cancel() cancel()
} }

View File

@ -63,6 +63,27 @@ func DeRegister(name string, addr string, port int) {
client.Agent().ServiceDeregister(fmt.Sprintf("%s-%s:%d", name, addr, port)) client.Agent().ServiceDeregister(fmt.Sprintf("%s-%s:%d", name, addr, port))
} }
//FindNode 查找节点
func FindNode(servicename string) (*consulapi.AgentService, error) {
// 创建连接consul服务配置
config := consulapi.DefaultConfig()
config.Address = consulAddr
client, err := consulapi.NewClient(config)
if err != nil {
log.WithFields(log.Fields{
"func": "FindNode",
}).Errorf("NewClient: %v", err)
}
services, _, err := client.Health().Service(servicename, "", true, nil)
if err != nil {
return nil, err
}
for _, service := range services {
return service.Service, nil
}
return nil, nil
}
//FindServer 从consul中发现服务 //FindServer 从consul中发现服务
func FindServer() { func FindServer() {
// 创建连接consul服务配置 // 创建连接consul服务配置

View File

@ -2,6 +2,8 @@ package sample
import ( import (
"context" "context"
"strconv"
"time"
pb "myschools.me/suguo/consul-demo/proto" pb "myschools.me/suguo/consul-demo/proto"
) )
@ -10,10 +12,15 @@ import (
type Server struct { type Server struct {
} }
var r int
//Say 实现微服务接口 //Say 实现微服务接口
func (s *Server) Say(c context.Context, req *pb.SayRequest) (*pb.SayResponse, error) { func (s *Server) Say(c context.Context, req *pb.SayRequest) (*pb.SayResponse, error) {
if r == 0 {
r = int(time.Now().Unix())
}
resp := &pb.SayResponse{ resp := &pb.SayResponse{
Reply: req.Name + req.Day, Reply: req.Name + req.Day + " " + strconv.Itoa(r),
} }
return resp, nil return resp, nil
} }