环境准备

基础环境

本人所使用的环境:

  • Ubuntu 20.04
  • pip 22.1.2
  • Python 3.8.13

安装gRPC

1
2
pip install grpcio
pip install grpcio-tools

基本使用

Service的定义

定义proto文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Service definition.
service Hello {
// Sends response
rpc SayHello (Request) returns (Response) {}

// The request message.
message Request {
string message = 1;
}

// The response message
message Response {
string message = 1;
}

生成gRPC代码

  • 生成gRPC代码的命令行格式如下:
1
python -m grpc_tools.protoc --proto_path=XXX --python_out=XXX --grpc_python_out=XXX @<filename>
  • grpc_tools.protoc命令的核心参数及其如下:
参数 是否必须 默认值 含义
-I, –proto_path 当前目录 待读取.protoc文件的路径,可多次声明,若有多个路径,则会依次查找。如果都没有找到,则在–descriptor_set_in参数所指定的目录中查找
–python_out / 生成的request类和response类的路径
–grpc_python_out / 生成的client类和server类的路径
@<filename> / 所读取的.proto文件的文件名。 如果指定了相对文件路径,则将在当前工作目录中搜索该文件。
  • 关于其它参数及其含义,可使用python -m grpc_tools.protoc --help指令查看。

运行gRPC

  1. 启动server
1
python server.py
  1. 新终端中启动client
1
python service.py
  • 可以在新终端中看到server response

添加新的方法

  1. 修改.proto文件内容,新增SayHelloAgain方法:
1
2
3
4
5
6
// Service definition.
service Hello {
// Sends response
rpc SayHello (Request) returns (Response) {}
// Sends another response
rpc SayHelloAgain (Request) returns (Response) {}
  1. 保存文件
  2. 重新生成gRPC代码:
1
python -m grpc_tools.protoc --proto_path=XXX --python_out=XXX --grpc_python_out=XXX @<filename>
  1. 修改server类,新增对应方法
1
2
3
4
5
class Hello(hello_pb2_grpc.HelloServicer):
def SayHello(self, request, context):
return hello_pb2.Request(message='Hello, %s!' % request.message)
def SayHelloAgain(self, request, context):
return hello_pb2.Response(message='Hello again, %s!' % request.message)
  1. 修改client类,新增对应方法
1
2
3
4
5
6
7
def run():
with grpc.insecure_channel('localhost:50051') as channel:
stub = hello_pb2_grpc.HelloStub(channel)
response = stub.SayHello(hello_pb2.Request(message='you'))
print("Hello client received: " + response.message)
response = stub.SayHelloAgain(helloworld_pb2.Request(message='you'))
print("Hello client received: " + response.message)
  1. 启动server
1
python server.py
  1. 新终端中启动client
1
python service.py
  • 最后可以在新终端中看到修改后的server response