└── study └── rpc ├── c.go(客戶端) ├── lib │ ├── test.pb.go(這個文件是protoc生成的) │ └── test.proto └── s.go(服務端)
syntax = "proto3"; package lib; service Test { rpc Say (Request) returns (Response) {} } message Request { string name = 1; } message Response { string age = 1; }
在rpc目錄下執行golang
protoc -I lib lib/test.proto --go_out=plugins=grpc:lib
package main import ( "context" "fmt" "google.golang.org/grpc" "net" "study/rpc/lib" ) type server struct { lib.UnimplementedTestServer } func (s *server) Say(ctx context.Context, in *lib.Request) (*lib.Response, error) { fmt.Println(in.GetName()) return &lib.Response{Age: in.GetName()}, nil } func main() { l, _ := net.Listen("tcp", ":10000") s := grpc.NewServer() lib.RegisterTestServer(s, &server{}) s.Serve(l) }
package main import ( "context" "fmt" "google.golang.org/grpc" "time" "study/rpc/lib" ) func main() { conn, _ := grpc.Dial(":10000", grpc.WithInsecure(), grpc.WithBlock()) defer conn.Close() c := lib.NewTestClient(conn) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() r, _ := c.Say(ctx, &lib.Request{Name: "c"}) fmt.Println(r.GetAge()) }