gRPC
gRPC 是 Google 开源的基于 Protobuf 和 Http2.0 协议的通信框架。
gRPC官网
python实现gRPC接口调用的方法步骤
2.1 安装第三方包:grpcio、protobuf、grpcio_tools
1 pip installgrpcio2 pip installprotobuf3 pip install grpcio_tools # python下的protoc编译器
2.2 编写proto文件
参考protobuf语法编写.proto文件
2.3 编译proto文件
将protoc文件转化为pb2和pb2_grpc文件,操作步骤如下:
命令:
1 python3 -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. xxx.proto -I=/workspace -I=xxx/yyy/
2
3 #说明:4 -I=:在proto文件中远程调用的内容,导入路径为实际调用的上一级目录即可。5 python_out:指定xxx_pb2.py的输出路径,编译生成处理protobuf相关的代码路径。传入.,则默认生成到当前目录。6 grpc_python_out:指定xxx_pb2_grpc.py的输出路径,编译生成处理grpc相关的代码路径,传入.,则默认生成到当前目录。7 grpc_tools.protoc:工具包,刚安装的。8 -I:这个参数指定协议文件的查找目录。9
10 # 生成的文件中:11 xxx_pb2.py:里面有消息序列化类。是用来和protobuf数据进行交互。12 xxx_pb2_grpc.py:包含了服务器Stub类和客户端Stub类,以及待实现的服务RPC接口。是用来和grpc进行交互。
# 若报错-缺少文件,则需要找对应文件,然后使用 "-I=" 导入
2.4 写server端代码
demo如下:
1 #coding:utf-8
2
3 importgrpc4 importjson5 from concurrent importfutures6 importxxx_pb2,yyy_pb2_grpc7
8 _HOST = ‘‘ #todo
9 _PORT = ‘‘ #todo
10
11
12 #实现 proto 文件中定义的 xxxServicer
13 classxxxServer(yyy_pb2_grpc.xxxServicer):14 #实现 proto 文件中定义的GRPC调用
15 defSendRequest(self, request, context):16 json_response =xxx_pb2.xxxResponse()17 json_response.rst_string = json.dumps({"ret": "Hi grpc"})18 returnjson_response19
20
21 defserve():22 #启动GRPC服务,监听特定的端口
23 server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) #多线程服务器
24 yyy_pb2_grpc.add_xxxServicer_to_server(xxxServer(), server) #注册本地服务
25 server.add_insecure_port("{0}:{1}".format(_HOST, _PORT)) #监听端口
26 server.start() #开始接收请求进行服务
27 try:28 whileTrue:29 time.sleep(60 * 60 * 24) #one day in seconds
30 exceptKeyboardInterrupt:31 server.stop(0)32
33
34 if __name__ == ‘__main__‘:35 serve()
2.5 写client端代码
demo如下:
1 #coding:utf-8
2
3 importgrpc4 importxxx_pb2, yyy_pb2_grpc5
6 _HOST = ‘‘ #todo
7 _PORT = ‘‘ #todo
8
9
10 defmain():11 with grpc.insecure_channel("{0}:{1}".format(_HOST, _PORT)) as channel:12 client = yyy_pb2_grpc.xxxStub(channel=channel)13 response =client.xxxMessage(xxx_pb2.xxxRequest())14 print("received:" + response.message +response.result)15
16
17 if __name__ == ‘__main__‘:18 main()
2.6 完成
gRPC四种通信方式
根据不同的业务场景, grpc 支持 4 种通信方式:
客服端一次请求, 服务器一次应答
客服端一次请求, 服务器多次应答(流式)
客服端多次请求(流式), 服务器一次应答
客服端多次请求(流式), 服务器多次应答(流式)
protoc
protoc3官网
protobuf数据格式
protobuf是Google开源的一款类似于Json,XML数据交换格式,其内部数据是纯二进制格式,不依赖于语言和平台,具有简单,数据量小,快速等优点。(是使用google规定的proto协议定义语言,之后使用proto的工具对代码进行‘编译’,生成对应的各个平台的源代码,后续可以使用这些源代码进行工作。)目前用于序列化于反序列化官方支持的语言有C++,C#,JAVA,PYTHON。适用于大小在1M以内的数据。可以使用prorobuf将内容序列化后保存在文件中,下次使用的时候,加载文件,反序列化后就可以直接使用了。
python-protobuf
在python里也需要proto文件生成对应的代码,才能通过grpc/restful协议调后端的代码
pb其实就是协议格式/内容,restful/rpc是协议
无关乎语言, 前端(python或go), 跟后端(go或者c++) 通信的时候,都要告知发送的内容的格式--这个格式就是pb
原文:https://www.cnblogs.com/sunshine-blog/p/12193064.html