gRPC go 入门示例
准备操作环境:macOS Big Sur安装 brew install protobuf安装 protoc-gen-go*go get google.golang.org/protobuf/cmd/protoc-gen-gogo get google.golang.org/grpc/cmd/prot
准备
操作环境:macOS Big Sur
- 安装
protobuf
brew install protobuf
- 安装
protoc-gen-go*
go get google.golang.org/protobuf/cmd/protoc-gen-go
go get google.golang.org/grpc/cmd/protoc-gen-go-grpc
编写 proto
syntax = "proto3";
option go_package = "github.com/feivxs/helloworld";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
生成 client & server 端接口
protoc \
--go_out=. --go_opt=paths=source_relative\
--go-grpc_out=. --go-grpc_opt=paths=source_relative\
helloworld/helloworld.proto
当上述命令成功执行后,会生成两个文件,分别为:
$ tree helloworld
helloworld
├── helloworld.proto
├── helloworld.pb.go (generated)
└── helloworld_grpc.pb.go (generated)
其中所生成的两个文件的作用分别为:
helloworld.pb.go生成 proto buffer 相关代码,包括请求、响应类型,以及发布、序列化等。helloworld_grpc.pb.go- 一个给 client 调用的接口类型(定义在 proto 中的方法)
- 一个给 server 端实现的接口类型(定义在 proto 中的方法)
编写 server 端实现接口代码
package main
import (
"context"
"log"
"net"
pb "github.com/feivxs/helloworld/helloworld"
"google.golang.org/grpc"
)
const (
port = ":50051"
)
// server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
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)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
编写 client 端调用接口代码
package main
import (
"context"
"log"
"os"
"time"
pb "github.com/feivxs/helloworld/helloworld"
"google.golang.org/grpc"
)
const (
address = "localhost:50051"
defaultName = "world"
)
func main() {
// Set up a connection to the server.
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)
// Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
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())
}