久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

如何用Python搭建gRPC服務(wù)

瀏覽:7日期:2022-06-15 15:42:12
目錄一、概述二、安裝python需要的庫(kù)三、定義gRPC的接口四、使用 protoc 和相應(yīng)的插件編譯生成對(duì)應(yīng)語(yǔ)言的代碼五、編寫(xiě)grpc的服務(wù)端代碼六、編寫(xiě)gRPC客戶端的代碼七、調(diào)用測(cè)試八、gRPC的使用總結(jié)一、概述

一個(gè)gRPC服務(wù)的大體結(jié)構(gòu)圖為:

如何用Python搭建gRPC服務(wù)

圖一表明,grpc的服務(wù)是跨語(yǔ)言的,但需要遵循相同的協(xié)議(proto)。相比于REST服務(wù),gPRC 的一個(gè)很明顯的優(yōu)勢(shì)是它使用了二進(jìn)制編碼,所以它比 JSON/HTTP 更快,且有清晰的接口規(guī)范以及支持流式傳輸,但它的實(shí)現(xiàn)相比rest服務(wù)要稍微要復(fù)雜一些,下面簡(jiǎn)單介紹搭建gRPC服務(wù)的步驟。

二、安裝python需要的庫(kù)

pip install grpcio

pip install grpcio-tools  

pip install protobuf

三、定義gRPC的接口

創(chuàng)建 gRPC 服務(wù)的第一步是在.proto 文件中定義好接口,proto是一個(gè)協(xié)議文件,客戶端和服務(wù)器的通信接口正是通過(guò)proto文件協(xié)定的,可以根據(jù)不同語(yǔ)言生成對(duì)應(yīng)語(yǔ)言的代碼文件。這個(gè)協(xié)議文件主要就是定義好服務(wù)(service)接口,以及請(qǐng)求參數(shù)和相應(yīng)結(jié)果的數(shù)據(jù)結(jié)構(gòu),下面是一個(gè)簡(jiǎn)單的例子。

syntax = 'proto3';​option cc_generic_services = true;​//定義服務(wù)接口service GrpcService { rpc hello (HelloRequest) returns (HelloResponse) {} //一個(gè)服務(wù)中可以定義多個(gè)接口,也就是多個(gè)函數(shù)功能}​//請(qǐng)求的參數(shù)message HelloRequest { string data = 1; //數(shù)字1,2是參數(shù)的位置順序,并不是對(duì)參數(shù)賦值 Skill skill = 2; //支持自定義的數(shù)據(jù)格式,非常靈活};​//返回的對(duì)象message HelloResponse { string result = 1; map<string, int32> map_result = 2; //支持map數(shù)據(jù)格式,類(lèi)似dict};​message Skill { string name = 1;};四、使用 protoc 和相應(yīng)的插件編譯生成對(duì)應(yīng)語(yǔ)言的代碼

python -m grpc_tools.protoc -I ./ --python_out=./ --grpc_python_out=. ./hello.proto

利用編譯工具把proto文件轉(zhuǎn)化成py文件,直接在當(dāng)前文件目錄下運(yùn)行上述代碼即可。

1.-I 指定proto所在目錄

2.-m 指定通過(guò)protoc生成py文件

3.--python_out指定生成py文件的輸出路徑

4.hello.proto 輸入的proto文件

執(zhí)行上述命令后,生成hello_pb2.py 和hello_pb2_grpc.py這兩個(gè)文件。

五、編寫(xiě)grpc的服務(wù)端代碼

#! /usr/bin/env python# coding=utf8​import timefrom 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,實(shí)現(xiàn)hello方法 ’’’ def __init__(self):pass​ def hello(self, request, context):’’’具體實(shí)現(xiàn)hello的方法,并按照pb的返回對(duì)象構(gòu)造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(): ’’’ 模擬服務(wù)啟動(dòng) :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()

在服務(wù)端側(cè),需要實(shí)現(xiàn)hello的方法來(lái)滿足proto文件中GrpcService的接口需求,hello方法的傳入?yún)?shù),是在proto文件中定義的HelloRequest,context是保留字段,不用管,返回參數(shù)則是在proto中定義的HelloResponse,服務(wù)啟動(dòng)的代碼是標(biāo)準(zhǔn)的,可以根據(jù)需求修改提供服務(wù)的ip地址以及端口號(hào)。

六、編寫(xiě)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(): ’’’ 模擬請(qǐng)求服務(wù)方法信息 :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(): ’’’ 模擬請(qǐng)求服務(wù)方法信息 :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()

客戶端側(cè)代碼的實(shí)現(xiàn)比較簡(jiǎn)單,首先定義好訪問(wèn)ip和端口號(hào),然后定義好HelloRequest數(shù)據(jù)結(jié)構(gòu),遠(yuǎn)程調(diào)用hello即可。需要強(qiáng)調(diào)的是,客戶端和服務(wù)端一定要import相同proto文件編譯生成的hello_pb2_grpc, hello_pb2模塊,即使服務(wù)端和客戶端使用的語(yǔ)言不一樣,這也是grpc接口規(guī)范一致的體現(xiàn)。

七、調(diào)用測(cè)試

先啟動(dòng)運(yùn)行服務(wù)端的代碼,再啟動(dòng)運(yùn)行客戶端的代碼即可。

八、gRPC的使用總結(jié) 定義好接口文檔 工具生成服務(wù)端/客戶端代碼 服務(wù)端補(bǔ)充業(yè)務(wù)代碼 客戶端建立 gRPC 連接后,使用自動(dòng)生成的代碼調(diào)用函數(shù) 編譯、運(yùn)行

以上就是如何用Python搭建gRPC服務(wù)的詳細(xì)內(nèi)容,更多關(guān)于Python搭建gRPC服務(wù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 华安县| 克拉玛依市| 新乡县| 溧阳市| 木里| 乌审旗| 石楼县| 靖宇县| 河西区| 丹东市| 北川| 大姚县| 神农架林区| 临洮县| 台山市| 望奎县| 无极县| 泗水县| 西城区| 武隆县| 文安县| 邓州市| 隆林| 婺源县| 湟源县| 浦江县| 德江县| 阜康市| 鲜城| 新密市| 乐昌市| 泸水县| 伊吾县| 潞城市| 腾冲县| 香格里拉县| 开江县| 普宁市| 全南县| 大同市| 枣庄市|