摘要:gRPC是一个高性能、通用的开源RPC框架,其由Google次要面向挪动利用开发并基于HTTP/2协定规范而设计,基于ProtoBuf序列化协定开发,且反对泛滥开发语言。
本文分享自华为云社区《用python搭建gRPC服务》,原文作者:井冈山_阳春 。
gRPC是一个高性能、通用的开源RPC框架,其由Google次要面向挪动利用开发并基于HTTP/2协定规范而设计,基于ProtoBuf序列化协定开发,且反对泛滥开发语言。一个gRPC服务的大体结构图为:
图一表明,grpc的服务是跨语言的,但须要遵循雷同的协定(proto)。相比于REST服务,gPRC 的一个很显著的劣势是它应用了二进制编码,所以它比 JSON/HTTP 更快,且有清晰的接口标准以及反对流式传输,但它的实现相比rest服务要略微要简单一些,上面简略介绍搭建gRPC服务的步骤。
1.装置python须要的库
pip install grpcio
pip install grpcio-tools
pip install protobuf
2.定义gRPC的接口
创立 gRPC 服务的第一步是在.proto 文件中定义好接口,proto是一个协定文件,客户端和服务器的通信接口正是通过proto文件协定的,能够依据不同语言生成对应语言的代码文件。这个协定文件次要就是定义好服务(service)接口,以及申请参数和相应后果的数据结构,具体的proto语法参见如下链接(https://www.jianshu.com/p/da7ed5914088),对于二维数组、字典等python中罕用的数据类型,proto语法的表白见链接(https://blog.csdn.net/xiaoxiaojie521/article/details/106938519),上面是一个简略的例子。
syntax = "proto3";
option cc_generic_services = true;
//定义服务接口
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;
};
3.应用 protoc 和相应的插件编译生成对应语言的代码
python -m grpc_tools.protoc -I ./ --python_out=./ --grpc_python_out=. ./hello.proto
利用编译工具把proto文件转化成py文件,间接在以后文件目录下运行上述代码即可。
- -I 指定proto所在目录
- -m 指定通过protoc生成py文件
- –python_out指定生成py文件的输入门路
- hello.proto 输出的proto文件
执行上述命令后,生成hello_pb2.py 和hello_pb2_grpc.py这两个文件。
4.编写grpc的服务端代码
#! /usr/bin/env python
# coding=utf8
import time
from concurrent import futures
import grpc
from gRPC_example import hello_pb2_grpc, hello_pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
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 test 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=10))
hello_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)
server.add_insecure_port('[::]:50052')
server.start()
print("start service...")
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
run()
在服务端侧,须要实现hello的办法来满足proto文件中GrpcService的接口需要,hello办法的传入参数,是在proto文件中定义的HelloRequest,context是保留字段,不必管,返回参数则是在proto中定义的HelloResponse,服务启动的代码是规范的,能够依据需要批改提供服务的ip地址以及端口号。
5.编写gRPC客户端的代码
#! /usr/bin/env python
# coding=utf8
import grpc
from gRPC_example import #! /usr/bin/env python
# coding=utf8
import grpc
from gRPC_example import hello_pb2_grpc, hello_pb2
def run():
'''
模仿申请服务办法信息
: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="xiao gang", skill=skill)
respnse = client.hello(request)
print("received:",respnse.result)
if __name__ == '__main__':
run()
def run():
'''
模仿申请服务办法信息
: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="xiao gang", skill=skill)
response = client.hello(request)
print("received:",response.result)
if __name__ == '__main__':
run()
客户端侧代码的实现比较简单,首先定义好拜访ip和端口号,而后定义好HelloRequest数据结构,近程调用hello即可。须要强调的是,客户端和服务端肯定要import雷同proto文件编译生成的hello_pb2_grpc, hello_pb2模块,即便服务端和客户端应用的语言不一样,这也是grpc接口标准统一的体现。
6.调用测试
先启动运行服务端的代码,再启动运行客户端的代码即可。
7.gRPC的应用总结
- 定义好接口文档
- 工具生成服务端/客户端代码
- 服务端补充业务代码
- 客户端建设 gRPC 连贯后,应用主动生成的代码调用函数
- 编译、运行
点击关注,第一工夫理解华为云陈腐技术~
发表回复