介紹
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 包
(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 main
import (
"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 main
import (
"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
全文完