Go grpc 基本使用
export GO111MODULE=on go get github.com/golang/protobuf/protoc-gen-go export PATH="$PATH:$(go env GOPATH)/bin" Go to src目录下 git clone -b v1.31.0 https://github.com/grpc/grpc-go mkdir grpc-go/examples/myproject/pb
创建proto文件:
syntax = "proto3"; package pb; option go_package = ".;pb"; message HelloRequest { string username = 1; } message HelloResponse { string message = 1; } message AddRequest { int64 first = 1; int64 second = 2; } message AddResponse { int64 result = 3; } message ClientStream { bytes stream = 1; } message ServerStream { bytes stream = 1; } service HelloService { rpc SayHello(HelloRequest) returns (HelloResponse){} rpc Chat(stream ClientStream) returns (stream ServerStream){} rpc Add(AddRequest) returns (AddResponse){} }
protoc --go_out=plugins=grpc:. hello.proto 生成 hello.pb.go文件
编写客户端和服务端程序
mkdir client
package main import ( "context" "fmt" "io" "time" pb "google.golang.org/grpc/examples/myproject/pb" "google.golang.org/grpc" ) func main() { conn, err := grpc.Dial("localhost:6001", grpc.WithInsecure()) if err != nil { fmt.Println(err.Error()) return } defer conn.Close() c := pb.NewHelloServiceClient(conn) r, err := c.Add(context.Background(), &pb.AddRequest{First: 88, Second: 88}) if err != nil { fmt.Println(err.Error()) return } fmt.Println(r.Result) // chat chatClilent, e := c.Chat(context.Background()) if e != nil { fmt.Println(e.Error()) return } go func() { for { stream, e := chatClilent.Recv() if e == io.EOF { fmt.Println("EOF") return } if e != nil { fmt.Println("cuowu") return } fmt.Println("receive from server:", stream.Stream) } }() chatClilent.Send(&pb.ClientStream{ Stream: newBytes(10, 9, 8, 7), }) select { case <-time.After(20 * time.Second): } } func newBytes(a ...byte) []byte { return a }
mkdir server
package main import ( "context" "fmt" "io" "net" pb "google.golang.org/grpc/examples/myproject/pb" "google.golang.org/grpc" ) type HelloService struct { } func (hs HelloService) Add(ctx context.Context, in *pb.AddRequest) (*pb.AddResponse, error) { return &pb.AddResponse{Result: in.First + in.Second}, nil } func (hs *HelloService) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) { return &pb.HelloResponse{Message: fmt.Sprintf("你好,%s", req.Username)}, nil } func (hs *HelloService) Chat(conn pb.HelloService_ChatServer) error { for { stream, err := conn.Recv() if err == io.EOF { fmt.Println("EOF") return nil } if err != nil { fmt.Println(err.Error()) return err } fmt.Println("receive from client:", stream.Stream) conn.Send(&pb.ServerStream{ Stream: newBytes(1, 2, 3, 4, 5), }) // 关闭连接 // return nil } return nil } func main() { lis, err := net.Listen("tcp", ":6001") if err != nil { fmt.Println(err.Error()) return } s := grpc.NewServer() pb.RegisterHelloServiceServer(s, &HelloService{}) s.Serve(lis) } func newBytes(a ...byte) []byte { return a }
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/13634140.html