consul-demo/client/main.go

51 lines
1.1 KiB
Go

package main
import (
"context"
"fmt"
"time"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"myschools.me/suguo/consul-demo/consul"
pb "myschools.me/suguo/consul-demo/proto"
)
func main() {
for {
time.Sleep(10 * time.Millisecond)
node, err := consul.FindNode("demo")
if err != nil {
log.WithFields(log.Fields{
"func": "main",
}).Errorf("%v", err)
fmt.Printf("%v\n", err)
continue
}
if node == nil {
fmt.Println("node is empty")
continue
}
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.DialContext(ctx, fmt.Sprintf("%s:%d", node.Address, node.Port), grpc.WithBlock(), grpc.WithInsecure(), grpc.WithBalancerName("round_robin"))
if err != nil {
cancel()
}
defer conn.Close()
c := pb.NewHelloClient(conn)
resp, err := c.Say(ctx, &pb.SayRequest{Name: "jiale", Day: "2008-08-08"})
if err != nil {
log.WithFields(log.Fields{
"func": "main",
}).Errorf("%v", err)
}
log.WithFields(log.Fields{
"func": "main",
}).Infof("%s", resp.Reply)
}
}