golang gRPC快速上手

1)安装protoc-go

go get -u google.golang.org/protobuf/cmd/protoc-gen-go
go install google.golang.org/protobuf/cmd/protoc-gen-go

2)安装protoc-grpc

go get -u google.golang.org/grpc/cmd/protoc-gen-go-grpc
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc

3)做一个proto文件

syntax = "proto3";

option go_package = ".;helloworld";

service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
string name = 1;
}

message HelloReply {
string message = 1;
}

4)生成go文件

protoc --go_out=. helloworld.proto

5)生成gprc文件

protoc --go-grpc_out=. helloworld.proto

6)服务器代码

type server struct {
   helloworld.UnimplementedGreeterServer
}

func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &helloworld.HelloReply{Message: "Hello " + in.GetName()}, nil
}
func main() {
   port := flag.Int("port", 50051, "The server port")
   flag.Parse()
   lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
   if err != nil {
   log.Fatalf("failed to listen: %v", err)
   }
   s := grpc.NewServer()
   helloworld.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)
   }
}

7)客户端代码

 

const (
defaultName = "world"
)

var (
addr = flag.String("addr", "localhost:50051", "the address to connect to")
name = flag.String("name", defaultName, "Name to greet")
)

func main() {
flag.Parse()
// Set up a connection to the server.
conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := helloworld.NewGreeterClient(conn)

// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &helloworld.HelloRequest{Name: *name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
}

8)运行

go run server/main.go
2023/02/01 22:17:53 server listening at [::]:50051
2023/02/01 22:19:28 Received: world


go run client/main.go
2023/02/01 22:19:28 Greeting: Hello world


欢迎转载,本文地址: https://blog.prodrich.com/detail/76/

带着使命来到世上的你,给他人提供价值,才有价值