2017-12-16
字数 695 阅读 12 评论 6
介绍 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)安装
1 go get -u google.golang.org/grpc
需要注意的是:这里安装的 grpc-go 只是一个第三方库,提供的是库函数接口,而不是二进制程序。因此,grpc-go 安装之后提供的是第三方包的作用。
在用户程序中,通常是通过下列方式来使用 grpc 包
(1)编写 .proto
文件
helloworld.proto
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 文件
1 protoc --go_out=plugin=grpc:. *.proto
或者
1 protoc --gofast_out=plugins=grpc:. *.proto
(3)编写 client 端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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 () { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v" , err) } defer conn.Close() c := pb.NewGreeterClient(conn) 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 端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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" ) type server struct {}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{}) 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
全文完!
如果你对我的文章感兴趣,欢迎留言或者关注我的专栏。
微信公众号:“知辉”
搜索“deliverit”或
扫描二维码