grpc+sonsul

client
package main

import (
"GoSonsulClient/pb"
"context"
"fmt"
"github.com/hashicorp/consul/api"
"google.golang.org/grpc"
"strconv"
)

func main() {
//初始化consul
consulConfig := api.DefaultConfig()
consulClient, err := api.NewClient(consulConfig)
if err != nil {
fmt.Println(err.Error())
}
services, _, err := consulClient.Health().Service("grpc And consul", "grpc", true, nil)
target := services[0].Service.Address + ":" + strconv.Itoa(services[0].Service.Port)
grpcConn, _ :=grpc.Dial(target, grpc.WithInsecure())
grpcClient := pb.NewHelloClient(grpcConn)
var person pb.Person
person.Name = "hello"
person.Age = 18
p, _ := grpcClient.SayHello(context.TODO(), &person)
fmt.Println(p)
}


server
package main

import (
"GoSonsul/pb"
"context"
"fmt"
"github.com/hashicorp/consul/api"
"google.golang.org/grpc"
"net"
)

type Children struct {
}

func (this *Children) SayHello(ctx context.Context, p *pb.Person) (*pb.Person, error) {
p.Name = "hello" + p.Name
return p, nil
}

func main() {
//初始化consul配置
consulCofig := api.DefaultConfig()
//创建consul对象
consulClent, err := api.NewClient(consulCofig)
if err != nil {
fmt.Println(err.Error())
return
}
//告诉consul,即将注册的服务的配置信息
reg := api.AgentServiceRegistration {
ID: "bj38",
Tags: []string {"grpc", "consul"},
Name: "grpc And consul",
Port: 8800,
Address: "127.0.0.1",
Check: &api.AgentServiceCheck{
CheckID: "consulGrpc",
TCP: "127.0.0.1:8800",
Timeout: "1s",
Interval: "1s",
},
}
consulClent.Agent().ServiceRegister(&reg)
grpcServer := grpc.NewServer()
pb.RegisterHelloServer(grpcServer, new(Children))
lister, err := net.Listen("tcp", "127.0.0.1:8800")
if err != nil {
return
}
defer lister.Close()
grpcServer.Serve(lister)
}


posted @ 2021-03-01 13:03  ConstType  阅读(39)  评论(0)    收藏  举报