grpc的部署与使用

1. grpc介绍

  在 gRPC 里客户端应用可以像调用本地对象一样直接调用另一台不同的机器上服务端应用的方法,使得您能够更容易地创建分布式应用和服务。与许多 RPC 系统类似,gRPC 也是基于以下理念:定义一个服务,指定其能够被远程调用的方法(包含参数和返回类型)。在服务端实现这个接口,并运行一个 gRPC 服务器来处理客户端调用。在客户端拥有一个存根能够像服务端一样的方法。(客户端:语言不限;服务端:语言不限)

2. grep安装

1
2
3
4
5

pip install grpcio

pip install grpcio-tools

3. grep使用

  • proto文件
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

syntax = "proto3";

// The greeting service definition.

service Greeter {

// Sends a greeting

rpc SayHello (HelloRequest) returns (HelloReply) {}

// Sends another greeting

rpc SayHelloAgain (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;

}

1
2
3

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./helloworld.proto

  • server.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

from concurrent import futures

import time



import grpc



import helloworld_pb2

import helloworld_pb2_grpc



_ONE_DAY_IN_SECONDS = 60 * 60 * 24





class Greeter(helloworld_pb2_grpc.GreeterServicer):



def SayHello(self, request, context):

return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)





def serve():

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)

server.add_insecure_port('[::]:50051')

server.start()

try:

while True:

time.sleep(_ONE_DAY_IN_SECONDS)

except KeyboardInterrupt:

server.stop(0)





if __name__ == '__main__':

serve()

  • client.py
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

from __future__ import print_function



import grpc



import helloworld_pb2

import helloworld_pb2_grpc





def run():

channel = grpc.insecure_channel('localhost:50051')

stub = helloworld_pb2_grpc.GreeterStub(channel)

response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))

print("Greeter client received: " + response.message)





if __name__ == '__main__':

run()