[go]grpc远程接口调用实现
// grpc序列化/反序列化成对应语言的对象 // 1.写idl(数据类型+方法) // 2.生成对应语言的序列化/反序列化代码 // 3.方法需要自己实现 // 环境(将gopath/bin加入path) //安装grpc引擎 go get -u google.golang.org/grpc //安装grpc-go插件(适配go语言) go get -u github.com/golang/protobuf/protoc-gen-go
//helloworld.proto // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; } service Greeter { // 定义sayhello方法 rpc SayHello (HelloRequest) returns (HelloReply) {} } protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
// server实现 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{} // 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实现 import ( "context" "log" "os" "time" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( address = "localhost:50051" defaultName = "world" ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure()) 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()) }
相关推荐
darren0zdc 2020-10-16
ltstud 2020-07-24
Erick 2020-07-18
wujingsheng0 2020-06-16
xmwang0 2020-06-14
极品小肥羊 2020-05-31
小小书童 2020-05-20
极品小肥羊 2020-04-23
小小书童 2020-04-10
君小黑 2020-03-04
naiwenw 2020-02-18
小小书童 2020-02-22
dabaoge 2020-02-16
小小书童 2019-12-23
dabaoge 2020-01-25
MAC2007 2020-01-17
duanlove技术路途 2019-12-28