Ok, 先来安装 gRPC 的开发环境,并且实践一下 Hello World 程序吧!
1. 开发环境
ENV: go version go1.11 windows/amd64
IDE: goland
使用 gRPC 需要安装以下开发环境
- Install gRPC (RPC框架)
- Install Protocol Buffers v3 (Google推出的一种数据描述语言)
- Install the protoc plugin for Go (编译器插件)
有关 gRPC、Protocol Buffers 的详细介绍会在后面章节补充, 这里先了解一下即可,主要目的先快速熟悉一下 gRPC.
2. 安装 gRPC
具体过程参考官方的 Quick Start 即可,下面给出一些遇到的一些问题和解决方法
如果通过官方推荐的方式,即(go get -u google.golang.org/grpc
)需要满足以下两个条件:
否则,是无法完成下载的, 错误可能为:
1
|
package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc"(https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout) |
解决方法参考:Golang安装gRPC报错问题的解决方法
3. Hello World Demo
Reference from Here and Here
3.1. Setup a repo
1
2
3
|
$ mkdir -p go-grpc/helloworld
$ cd go-grpc
$ go mod init go-grpc
|
Note: goland 使用 Go Modules 时需要启用:Go Module(vgo) (Ctrl+Alt+S -> Go -> Go Module(vgo) -> Enable ✔
)
3.2. Make a file helloworld/helloworld.proto
for protocol buffers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// gRPC: helloworld demo
syntax = "proto3";
package helloworld;
// The greeting service definition.
service Greeter {
// Send a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The resquest message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
|
3.3. Generate a go file from protocol buffers
1
2
3
|
$ protoc --go_out=plugins=grpc:. helloworld/helloworld.proto
$ ls helloworld
helloworld.pb.go helloworld.proto
|
执行完成后会生成一个:helloworld.pb.go 文件
3.4. Make a gRPC server file server/main.go
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
38
39
40
41
|
/*
* 说明:gRPC: helloworld demo
* 作者:zhe
* 时间:2018-09-05 1:40 PM
* 更新:
*/
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
pb "go-grpc/helloworld"
)
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 server: %v", err)
}
}
|
3.5. Make a gRPC client file client/main.go
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
38
39
40
41
42
43
44
45
46
|
/*
* 说明:gRPC: helloworld demo
* 作者:zhe
* 时间:2018-09-05 1:46 PM
* 更新:
*/
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/grpc"
pb "go-grpc/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]
}
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: %v", r.Message)
}
|
3.6. Try it out!
1
|
$ go run server/main.go
|
Open a new termial
1
2
|
$ go run client/main.go
2018/09/05 16:16:15 Greeting: Hello world
|
Maybe, you can try more. Continue…
4. Update a gRPC service
4.1. Update .proto
给 helloworld/helloworld.proto
再添加一个方法:SayHelloAgain
, request and response 类型同 SayHello 函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// gRPC: helloworld demo
syntax = "proto3";
package helloworld;
// The greeting service definition.
service Greeter {
// Send a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The resquest message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
|
4.2. Generate gRPC code
1
|
$ protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
|
4.3. Update and run the application
4.3.1. Update Server
给 type server struct{}
添加方法:SayHelloAgain, 即:
1
2
3
|
func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello again " + in.Name}, nil
}
|
4.3.2. Update Client
在客户端程序中调用 SayHelloAgain
:
1
2
3
4
5
|
r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
|
4.4. Run
run the server:
1
|
[zhe@zhe go-grpc]$ go run server/main.go
|
run the client:
1
2
3
|
[zhe@zhe go-grpc]$ go run client/main.go
2018/09/05 16:35:03 Greeting: Hello world
2018/09/05 16:35:03 Greeting: Hello again world
|
Now, the end.
5. See Also
Thanks to the authors 🙂