当前位置: 首页 > 后端技术 > Python

技术实践:教你用Python搭建gRPC服务

时间:2023-03-25 22:52:12 Python

摘要:gRPC是一个高性能、通用的开源RPC框架,由Google设计,主要用于移动应用开发,基于HTTP/2协议标准,基于ProtoBuf序列化协议开发,支持多种开发语言。本文分享自华为云社区《用python搭建gRPC服务》,原作者:井冈山_阳春。gRPC是一个高性能、通用的开源RPC框架。它由谷歌设计,主要用于移动应用程序开发,基于HTTP/2协议标准。基于ProtoBuf序列化协议开发,支持多种开发语言。gRPC服务的一般结构图如下:图1表明grpc服务是跨语言的,但需要遵循相同的协议(proto)。与REST服务相比,gPRC的一个明显优势是它使用了二进制编码,因此比JSON/HTTP速度更快,并且接口规范清晰,支持流式传输,但其实现比rest服务贵了一点复杂的。下面简单介绍一下搭建gRPC服务的步骤。1、安装pythonpipinstallgrpciopipinstallgrpcio-toolspipinstallprotobuf2需要的库。定义gRPC的接口创建gRPC服务的第一步是在.proto文件中定义接口。proto是一个协议文件,客户端和服务端通过proto文件约定通信接口,可以根据不同的语言生成相应语言的代码文件。这个协议文件主要定义了服务(service)接口,以及请求参数和对应结果的数据结构。具体的proto语法可以参考以下链接(https://www.jianshu.com/p/da7...),关于python中二维数组、字典等常用数据类型,表达式为proto语法可以在链接(https://blog.csdn.net/xiaoxia...)中找到,下面是一个简单的例子。syntax="proto3";optioncc_generic_services=true;//定义服务接口serviceGrpcService{rpchello(HelloRequest)returns(HelloResponse){}//一个服务可以定义多个接口,即多个函数}//请求参数消息HelloRequest{stringdata=1;//数字1和2是参数的位置顺序,不是赋值给参数skillskill=2;//支持自定义数据格式,非常灵活};//返回的对象消息HelloResponse{stringresult=1;mapmap_result=2;//支持地图数据格式,类似dict};messageSkill{stringname=1;};3.使用protoc和对应的插件编译生成对应语言的代码python-mgrpc_tools.protoc-I./--python_out=./--grpc_python_out=../hello.proto使用编译工具将proto文件转换成py文件,直接在当前文件目录下运行上面的代码。-I指定proto所在目录-m指定通过protoc生成py文件--python_out指定生成的py文件hello.proto的输出路径执行以上命令后,hello_pb2.py和hello_pb2_grpc这两个文件。py生成。4.编写grpc服务端代码#!/usr/bin/envpython#coding=utf8importtimefromconcurrentimportfuturesimportgrpcfromgRPC_exampleimporthello_pb2_grpc,hello_pb2_ONE_DAY_IN_SECONDS=60*60*24classTestService(hello_pb2_grpc.GrpcServiceServicer):'''InheritGrpcServiceServicer,实现hello方法'''def__init__(self):passdefhello(self,request,context):'''具体实现hello的方法,根据pb返回对象构造HelloResponsereturn:paramrequest::paramcontext::return:'''result=request.data+request.skill.name+"这是gprc测试服务"list_result={"12":1232}returnhello_pb2.HelloResponse(result=str(result),map_result=list_result)defrun():'''模拟服务启动:return:'''server=grpc.server(futures.ThreadPoolExecutor(max_workers=10))hello_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)server.add_insecure_port('[::]:50052')server.start()print("startservice...")try:whileTrue:time.sleep(_ONE_DAY_IN_SECONDS)exceptKeyboardInterrupt:server.stop(0)if__name__=='__main__':run()服务端需要实现hello方法,满足proto文件中GrpcService的接口要求。hello方法的传入参数是proto文件中定义的HelloRequest。proto中定义的HelloResponse,服务启动代码是标准的,可以根据需要修改服务的ip地址和端口号5.编写gRPC客户端的代码#!/usr/bin/envpython#coding=utf8importgrpcfromgRPC_exampleimport#!/usr/bin/envpython#coding=utf8importgrpcfromgRPC_exampleimporthello_pb2_grpc,hello_pb2defrun():'''模拟请求服务方法信息:return:'''conn=grpc.insecure_channel('localhost:50052')client=hello_pb2_grpc.GrpcServiceStub(channel=conn)skill=hello_pb2.Skill(name="engineer")request=hello_pb2.HelloRequest(data="xiaogang",skill=skill)respnse=client.hello(request)print("received:",respnse.result)if__name__=='__main__':run()defrun():'''模拟请求服务方法信息:return:'''conn=grpc.insecure_channel('localhost:50052')client=hello_pb2_grpc.GrpcServiceStub(channel=conn)skill=hello_pb2.Skill(name="engineer")request=hello_pb2.HelloRequest(data="xiaogang",skill=skill)response=client.hello(request)print("received:",response.result)if__name__=='__main__':执行run()客户端代码比较简单,首先定义Yihao访问ip和端口号,然后定义HelloRequest数据结构,远程调用hello。需要强调的是,客户端和服务端必须导入从同一个proto文件编译出来的hello_pb2_grpc和hello_pb2模块,即使服务端和客户端使用的语言不同,这也是grpc接口规范一致的体现。6.调用测试,先启动并运行服务端的代码,再启动并运行客户端的代码。7、gRPC使用总结定义接口文件工具生成服务端/客户端代码服务端补充业务代码客户端建立gRPC连接后,使用自动生成的代码调用函数编译运行。点击关注,第一时间了解华为云。技术~