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

6次阅读

共计 3562 个字符,预计需要花费 9 分钟才能阅读完成。

摘要 :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 文件,间接在以后文件目录下运行上述代码即可。

  1. -I 指定 proto 所在目录
  2. -m 指定通过 protoc 生成 py 文件
  3. –python_out 指定生成 py 文件的输入门路
  4. 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 的应用总结

  1. 定义好接口文档
  2. 工具生成服务端 / 客户端代码
  3. 服务端补充业务代码
  4. 客户端建设 gRPC 连贯后,应用主动生成的代码调用函数
  5. 编译、运行

点击关注,第一工夫理解华为云陈腐技术~

正文完
 0