天天看點

技術實踐:教你用Python搭建gRPC服務

摘要:gRPC是一個高性能、通用的開源RPC架構,其由Google主要面向移動應用開發并基于HTTP/2協定标準而設計,基于ProtoBuf序列化協定開發,且支援衆多開發語言。

本文分享自華為雲社群《用python搭建gRPC服務》,原文作者:井岡山_陽春 。

gRPC是一個高性能、通用的開源RPC架構,其由Google主要面向移動應用開發并基于HTTP/2協定标準而設計,基于ProtoBuf序列化協定開發,且支援衆多開發語言。一個gRPC服務的大體結構圖為:

技術實踐:教你用Python搭建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. 編譯、運作

點選關注,第一時間了解華為雲新鮮技術~