golang grpc demo
1、安装 gRPC 和 Protobuf
protobuf 安装链接:https://liqiang.io/post/install-protobuf-in-centos-f0a9b926
protoc-gen-go 二进制构建
git clone https://github.com/golang/protobuf.git cd protobuf go build protoc-gen-go/main.go -o /bin/protoc-gen-go
2、定义.proto 文件
mkdir helloworld cd helloworld #cat hello.proto syntax = "proto3"; package helloworld; option go_package = "./helloworld"; // 定义服务 service Greeter { // 定义方法 rpc SayHello (HelloRequest) returns (HelloReply) {} } // 定义请求参数 message HelloRequest { string name = 1; } // 定义响应参数 message HelloReply { string message = 1; }
3、生成 golang 代码
cd .. protoc -I helloworld/ helloworld/hello.proto --go_out=plugins=grpc:helloworld
4、实现服务器
cd helloworld #cat server.go package main import ( "context" "log" "net" "google.golang.org/grpc" pb "helloworld/helloworld" // 导入生成的代码 ) const ( port = ":50051" ) // 定义服务 type server struct { pb.UnimplementedGreeterServer } // 实现 SayHello 方法 func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf("Received: %v", in.GetName()) return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil } func main() { // 监听端口 lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } // 创建 grpc 服务 s := grpc.NewServer() // 注册服务 pb.RegisterGreeterServer(s, &server{}) log.Printf("server listening at %v", lis.Addr()) // 启动服务 if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
5、实现客户端
#cat client.go package main import ( "context" "log" "os" "time" "google.golang.org/grpc" pb "helloworld/helloworld" // 导入生成的代码 ) const ( address = "localhost:50051" defaultName = "world" ) func main() { // 建立连接 conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() // 创建客户端 c := pb.NewGreeterClient(conn) // 设置超时 ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() // 构建请求 name := defaultName if len(os.Args) > 1 { name = os.Args[1] } r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.GetMessage()) }
6、运行示例
go mod init go mod tidy go mod vendor # server #go run server.go 2023/05/24 19:00:21 server listening at [::]:50051 2023/05/24 19:00:24 Received: world # client #go run client.go 2023/05/24 19:00:24 Greeting: Hello world