安装gRPC runtime
1 | go get google.golang.org/grpc |
如果不能翻墙,可以通过golang 中国下载,將安装包解压到GOPATH/src目录下,然后执行go install google.golang.org/grpc
安装
安装protobuf buffer
下载protobuf安装包,解压后,编译
1 | ./configure |
执行protoc --version
验证有没有安装成功
如果报找不到动态链接库的错误,在/etc/ld.so.conf.d/目录下新建一个protoc.conf文件,將动态库的目录添加进去,再执行sudo ldconfig
安装proto插件和库
1 | go get -u github.com/golang/protobuf/proto |
安装完之后,需要將GOBIN添加进PATH路径1
2echo "export PATH = $PATH:$GOBIN" >> ~/.bashrc
source ~/.bashrc
示例程序
协议文件
创建一个文件夹用来存放协议文件,protocol/helloworld.proto1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21syntax = "proto3";
option objc_class_prefix = "HLW";
package protocol;
// 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;
}
使用protoc命令生成go文件1
protoc --go_out=plugins=grpc:. helloworld.proto
服务器程序
server.go1
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
30package main
import (
"log"
"net"
pb "protocol"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
const (
port = ":5001"
)
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{})
s.Serve(lis)
}
客户端程序
client.go1
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
34package main
import (
"log"
"os"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "protocol"
)
const (
address = "localhost:5001"
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)
}
先运行服务器,再运行客户端
1 | go run server.go & |
可以看到rpc调用成功