最近学习了python 如何提供gRPC 服务, 这里以官方教程 和博客 为参考,简单记录一下具体步骤
0. 安装相关依赖包:grpcio、protobuf、grpcio-tools
1. 定义proto文件, 这里命名为`hello.proto`
syntax = "proto3";
package hello;
//定义服务接口
service GrpcService {
rpc hello (HelloRequest) returns (HelloResponse) {} //一个服务中可以定义多个接口,也就是多个函数功能
}
//请求的参数
message HelloRequest {
string data = 1; //数字1,2是参数的位置顺序,并不是对参数赋值
Skill skill = 2; //支持自定义的数据格式,非常灵活
};
//返回的对象
message HelloResponse {
string result = 1;
map<string, int32> map_result = 2; //支持map数据格式,类似dict
};
message Skill {
string name = 1;
};
2. 编译步骤1中生成的proto文件,-I 指定proto所在目录, 编译成功之后,在python_out指定的路径会生成addressbook_pb2.py文件, 在grpc_python_out指定的路径会生成addressbook_pb2_grpc.py文件
python -m grpc_tools.protoc -I=./ --python_out=./ --grpc_python_out=./ ./hello.proto
3. 在Python中实现服务接口,定义如下`server.py`
import time
from concurrent import futures
import grpc
import hello_pb2_grpc, hello_pb2
class TestService(hello_pb2_grpc.GrpcServiceServicer):
'''
继承GrpcServiceServicer,实现hello方法
'''
def __init__(self):
pass
def hello(self, request, context):
'''
具体实现hello的方法,并按照pb的返回对象构造HelloResponse返回
:param request:
:param context:
:return:
'''
result = request.data + request.skill.name + " this is gprc hello service"
list_result = {"12": 1232}
return hello_pb2.HelloResponse(result=str(result),
map_result=list_result)
def run():
'''
模拟服务启动
:return:
'''
server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
hello_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)
server.add_insecure_port('[::]:50051')
server.start()
print("start grpc service...")
server.wait_for_termination()
if __name__ == '__main__':
run()
成功运行server.py之后,可以再定义个client.py来测试是否调通服务
import grpc
import hello_pb2_grpc, hello_pb2
def run():
'''
模拟请求服务方法信息
:return:
'''
conn=grpc.insecure_channel('127.0.0.1:50051')
client = hello_pb2_grpc.GrpcServiceStub(channel=conn)
skill = hello_pb2.Skill(name="coding")
request = hello_pb2.HelloRequest(data="hello grpc", skill=skill)
response = client.hello(request)
print("received:",response.result)
if __name__ == '__main__':
run()
运行client.py 将会打印出如下结果