gRPC 是一款高性能、开源的 RPC 框架,产自 Google,基于 ProtoBuf 序列化协议进行开发,支持多种语言(Golang、Python、Java等),本篇只介绍 Python 的 gRPC 使用。由于 gRPC 对 HTTP/2 协议的支持使其在 Android、IOS 等客户端后端服务的开发领域具备良好的前景。gRPC 提供了一种简单的方法来定义服务,同时客户端能够充分利用 HTTP/2 stream 的特性,从而有助于节省带宽、下降 TCP 的链接次数、节省CPU的使用等。python
$ pip install grpcio后端
$ pip install protobuf框架
$ pip install grpcio-tools工具
下面咱们使用 gRPC 定义一个接口,该接口实现对传入的数据进行大写的格式化处理。性能
建立项目 python demo 工程:spa
- client目录下的 main.py 实现了客户端用于发送数据并打印接收到 server 端处理后的数据
syntax = "proto3"; package example; service FormatData { rpc DoFormat(Data) returns (Data){} } message Data { string text = 1; }
$ python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./data.proto #在 example 目录中执行编译,会生成:data_pb2.py 与 data_pb2_grpc.pycode
#! /usr/bin/env python # -*- coding: utf-8 -*- import grpc import time from concurrent import futures from example import data_pb2, data_pb2_grpc _ONE_DAY_IN_SECONDS = 60 * 60 * 24 _HOST = 'localhost' _PORT = '8080' class FormatData(data_pb2_grpc.FormatDataServicer): def DoFormat(self, request, context): str = request.text return data_pb2.Data(text=str.upper()) def serve(): grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4)) data_pb2_grpc.add_FormatDataServicer_to_server(FormatData(), grpcServer) grpcServer.add_insecure_port(_HOST + ':' + _PORT) grpcServer.start() try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: grpcServer.stop(0) if __name__ == '__main__': serve()
#! /usr/bin/env python # -*- coding: utf-8 -*- import grpc from example import data_pb2, data_pb2_grpc _HOST = 'localhost' _PORT = '8080' def run(): conn = grpc.insecure_channel(_HOST + ':' + _PORT) client = data_pb2_grpc.FormatDataStub(channel=conn) response = client.DoFormat(data_pb2.Data(text='hello,world!')) print("received: " + response.text) if __name__ == '__main__': run()
- 先启动 server,以后再执行 client