golang 进行grpc调用
参考https://blog.csdn.net/qq_32744005/article/details/105606383
go get google.golang.org/grpc
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
[root@localhost helloworld]# echo $GOPATH
/usr/local/go/workspacego
cd /usr/local/go/workspacego/src/google.golang.org/grpc/examples/helloworld/helloworld
[root@localhost helloworld]# cat /data/wwwroot/grpcdemo/client.go
package main import ( "context" "log" "os" "time" "google.golang.org/grpc" //grpc 的包 pb "google.golang.org/grpc/examples/helloworld/helloworld" //生产的中间文件 ) const ( address = "localhost:50051" //ip + port 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()) }
[root@localhost helloworld]# cat /data/wwwroot/grpcdemo/server.go
package main import ( "context" "log" "net" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) 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) } }
#go run /data/wwwroot/grpcdemo/server.go
另外发起一个终端
#go run /data/wwwroot/grpcdemo/client.go
服务端返回
2020/05/12 17:33:56 Received: world
客户端返回
2020/05/12 17:33:56 Greeting: Hello world