gRPC
2021/4/10 18:43:54
本文主要是介绍gRPC,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
gRPC的使用通常包括如下几个步骤:
- 通过protobuf来定义接口和数据类型
- 编写gRPC server端代码
-
编写gRPC client端代码
RPC(Remote Procedure Call)即:远程过程调用,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。使用的时候,客户端调用server端提供的接口就像是调用本地的函数一样。
- RPC遵从server/client模型。gRPC 由 Google 开发。
- 1.安装gRPC
pip install -U grpcio pip install -U grpcio-tools pip install -U protobuf
实例:用 gRPC server端部署一个随机森林分类器,client 端发起请求预测鸢尾花类型。
训练一个随机森林分类模型,把训练好的模型保存为pkl文件。
# train_model.py from sklearn import datasets from sklearn.pipeline import Pipeline import joblib from sklearn.ensemble import RandomForestClassifier def main(): clf = RandomForestClassifier() p = Pipeline([('clf', clf)]) p.fit(X, y) filename_p = 'IrisClassifier.pkl' joblib.dump(p, filename_p) print('Model saved!') if __name__ == "__main__": iris = datasets.load_iris() X, y = iris.data, iris.target main()
1、通过protobuf定义接口和数据类型
(1)新建一个iris_demo.proto文件
syntax = "proto3"; package iris; message IrisPredictRequest {// 定义参数1 float sepal_length = 1;//参数字段1 float sepal_width = 2;//参数字段2 float petal_length = 3;//参数字段3 float petal_width = 4;//参数字段4 } message IrisPredictResponse {// 定义参数1 int32 species = 1; } service IrisPredictor{// 定义服务 rpc predict_iris_species(IrisPredictRequest) returns (IrisPredictResponse){} }
proto文件格式
1.头部的syntax 注明版本号必须为 "proto3"
2.中间的 message 定义了predict_iris_species方法的参数IrisPredictRequest和IrisPredictResponse,还有参数字段的类型。
3.尾部的 service 定义一个服务IrisPredictor,其中包括 1 个predict_iris_species的RPC方法。这里可以定义多个RPC方法,在 message 中定义对应的参数即可。
2、使用gRPC protobuf生成Python的库函数
python -m grpc_tools.protoc -I=. --python_out=. --grpc_python_out=. ./iris_demo.proto
3、写一个服务器
这里的重点是定义 IrisPredictor 类的 predict_iris_species 方法,然后用 iris_demo_pb2_grpc.py 中的 add_IrisPredictorServicer_to_server 方法将 IrisPredictor 添加到 server。serve 函数里定义了 gRPC 的运行方式,使用 4 个 worker 的线程池。
# iris_prediction_server.py import grpc from concurrent import futures import time import joblib import iris_demo_pb2 import iris_demo_pb2_grpc import predict_iris from sklearn.ensemble import RandomForestClassifier class IrisPredictor(iris_demo_pb2_grpc.IrisPredictorServicer): @classmethod def get_trained_model(cls): cls._model = joblib.load('IrisClassifier.pkl') return cls._model def predict_iris_species(self, request, context): model = self.__class__.get_trained_model() sepal_length = request.sepal_length sepal_width = request.sepal_width petal_length = request.petal_length petal_width = request.petal_width result = model.predict( [[sepal_length, sepal_width, petal_length, petal_width]]) response = iris_demo_pb2.IrisPredictResponse(species=result[0]) return response # not sure def run(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=4)) iris_demo_pb2_grpc.add_IrisPredictorServicer_to_server( IrisPredictor(), server) server.add_insecure_port('[::]:50055') server.start() print("grpc server start...") print("Listening on port 50055") server.wait_for_termination() if __name__ == '__main__': run()
4、写一个客户端
客户端的逻辑更加简单,连上gRPC服务,然后发起调用。
# iris_prediction_client.py import grpc import iris_demo_pb2 import iris_demo_pb2_grpc def run(): channel = grpc.insecure_channel('localhost:50055') stub = iris_demo_pb2_grpc.IrisPredictorStub(channel) request = iris_demo_pb2.IrisPredictRequest( sepal_length=6.7, sepal_width=3.0, petal_length=5.2, petal_width=2.3) response = stub.predict_iris_species(request) print('The prediction is :', response.species) if __name__ == '__main__': run()
5、调用 RPC
先开启服务端
$ python iris_prediction_server.py grpc server start... Listening on port 50055
另起一个terminal执行客户端代码,调用gRPC服务,预测结果如下:
$ python iris_prediction_client.py The prediction is : 2
非原创__________________
https://mp.weixin.qq.com/s/WGCoejI6zzEXTJ4fvgwDGg
https://www.jianshu.com/p/9c947d98e192
——————————————————————————————————————————————————————————————
学习使用心得:
这篇关于gRPC的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升