如何用Python搭建gRPC服務

2022-09-25 09:27:11 字數 3679 閱讀 7678

目錄

乙個grpc服務的大體結構圖為:

圖一表明,grpc的服務是跨語言的,但需要遵循相同的協議(proto)。相比於rest服務,gprc 的乙個很明顯的優勢是它使用了二進位制編碼,所以它比 json/http 更快,且有清晰的介面規範以及支援流式傳輸,但它的實現相比rest服務要稍微要複雜一些,下面簡單介紹搭建grpc服務的步驟。

pip install grpcio

pip install grpcio-tools  

pip install protobuf

建立 grpc 服務的第一步是在.proto 檔案中定義好介面,pro程式設計客棧to是乙個協議檔案,客戶端和伺服器的通訊介面正是通過proto檔案協定的,可以根據不同語言生成對應語言的**檔案。這個協議檔案主要就是定義好服務(service)介面,以及請求引數和相應結果的資料結構,下面是乙個簡單的例子。

syntax = "proto3";

​option cc_generic_services = true;

​//定義服務介面

service grpcservice //乙個服務中可以定義多個介面,也就是多個函式功能}​

//請求的引數

message hellorequest ;

​//返回的物件

message helloresponse ;

​message skill ;

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這兩個檔案。

#! /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 =

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位址以及埠號。

#! /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介面規範一致的體現。

先啟動執行服務端的**,再啟動執行客戶端的**即可。

如何用WordPress搭建部落格

所以這一篇介紹 的一般搭建過程。這是科普文,如果你對技術並不感興趣,可以直接按ctrl w.如果你是非開發人員,或者是學習建站的新手,那麼這篇文章挺適合你的。好了,假如你會一些寫網頁,而後台開發技術 如j a,python,php,asp.net等 是入門級水平,現在你想要自己搭建乙個部落格,那麼現...

gRPC 如何使用python表示多維陣列

在使用grpc作為遠端呼叫框架時,如何使用python來表示多維陣列呢?grpc中定義proto檔案時,有乙個引數是repeated,用來表示重複的資料型別,使用這個引數可以表示list型別。如下,我想表示乙個三維陣列,這個陣列表示的是乙個三通道rgb彩色影象,proto檔案如下所示,proto檔案...

如何用 Node Vue 搭建自己的部落格

為什麼選擇使用 node vue 搭建自己部落格,而不使用如 wordpress 等成熟的模板呢?我們使用 node.js 自己寫介面,vue 做前端渲染,可以讓我們更了解乙個 從後台搭建到前端渲染的過程,形成乙個知識的閉環,可以更有效提公升我們工做效率。文章主要內容包括 伺服器搭建,ssl 證書配...