grpc-go|grpc-go 的安装和使用

介绍 Google 原生的 grpc 框架 是用 C 语言实现的,其默认包含了多种语言(cpp, ruby, python, c# 等)的实现,因而可以支持多种语言的 grpc 调用。但是默认没有提供 Go 和 Java 两种语言的 GRPC 实现。虽然如此,Google 官方在另外的单独的仓库中提供了 Go 语言版本的 GRPC 实现,也即 grpc-go(注:java 版的在 grpc-java 中),它们都在独立的 Repository 中。
这篇文章就来介绍下如何安装和使用 grpc-go,并构建基于 grpc-go 的程序。
grpc-go 安装 官方 repo 地址:https://github.com/grpc/grpc-go
(1) 依赖
需要至少 go 1.7+,以及 gRPC
(2)安装

go get -u google.golang.org/grpc

需要注意的是:这里安装的 grpc-go 只是一个第三方库,提供的是库函数接口,而不是二进制程序。因此,grpc-go 安装之后提供的是第三方包的作用。
【grpc-go|grpc-go 的安装和使用】在用户程序中,通常是通过下列方式来使用 grpc 包
(1)编写 .proto 文件
helloworld.proto
syntax = "proto3"; option java_multiple_files = true; option java_package = "io.grpc.examples.helloworld"; option java_outer_classname = "HelloWorldProto"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} }// The request message containing the user's name. message HelloRequest { string name = 1; }// The response message containing the greetings message HelloReply { string message = 1; }

(2)编译 .proto 文件
protoc --go_out=plugin=grpc:. *.proto

或者
protoc --gofast_out=plugins=grpc:. *.proto

(3)编写 client 端代码
package mainimport ( "log" "os""golang.org/x/net/context" "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] } r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) }

注:以上内容来自 grpc-go 源码目录中的 examples/helloworld/greeter_client/main.go
(4)编写 server 端代码
package mainimport ( "log" "net""golang.org/x/net/context" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" "google.golang.org/grpc/reflection" )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) { return &pb.HelloReply{Message: "Hello " + in.Name}, 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{}) // Register reflection service on gRPC server. reflection.Register(s) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }

注:以上内容来自 grpc-go 源码目录中的 examples/helloworld/greeter_server/main.go
全文完

    推荐阅读