搭建python版本的grpc服務(wù)

grpc簡介

gRPC是一個高性能、通用的開源RPC框架,其由Google主要面向移動應(yīng)用開發(fā)并基于HTTP/2協(xié)議標(biāo)準(zhǔn)而設(shè)計(jì),基于ProtoBuf序列化協(xié)議開發(fā),且支持眾多開發(fā)語言。具體大家可以在gRPC的官網(wǎng)查看。

搭建python grpc服務(wù)

  • 我們用的python3.6,第一步淡然是安裝python需要的庫
   pip install grpcio
   pip install grpcio-tools  主要是為了將pb編譯成python
   pip install protobuf
  • 開發(fā)protobuf文件,protobuf版本用的proto3。名稱位test.proto
syntax = "proto3";

option cc_generic_services = true;

service GrpcService {
    rpc hello (HelloRequest) returns (HelloResponse) {}
}

//請求的pb
message HelloRequest {
    string data = 1;
};

//返回的對象
message HelloResponse {
    string result = 1;
};
  • 開發(fā)完成后,我們要將pb文件轉(zhuǎn)化成python文件,直接在當(dāng)前文件目錄下面執(zhí)行
 python -m grpc_tools.protoc -I./ --python_out=./ --grpc_python_out=./  ./test.proto

執(zhí)行完后會生成一個test_pb2.py和test_pb3_grpc.py

  • 接下來我們開發(fā)grpc的服務(wù)端,service.py
#! /usr/bin/env python
# coding=utf8

import time
from concurrent import futures

import grpc

from service import test_pb2_grpc, test_pb2

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class TestService(test_pb2_grpc.GrpcServiceServicer):
    '''
    繼承GrpcServiceServicer,實(shí)現(xiàn)hello方法
    '''
    def __init__(self):
        pass

    def hello(self, request, context):
        '''
        具體實(shí)現(xiàn)hello的方法,并按照pb的返回對象構(gòu)造HelloResponse返回
        :param request: 
        :param context: 
        :return: 
        '''
        result = request.data + " this is gprc test service"
        return test_pb2.HelloResponse(result=str(result))



def run():
    '''
    模擬服務(wù)啟動
    :return: 
    '''
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    test_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)
    server.add_insecure_port('127.0.0.1:9098')
    server.start()
    print("start service...")
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    run()
  • 繼續(xù)開發(fā)grpc的客戶端請求,client.py
#! /usr/bin/env python
# coding=utf8

import grpc

from service import test_pb2_grpc, test_pb2


def run():
    '''
    模擬請求服務(wù)方法信息
    :return: 
    '''
    conn=grpc.insecure_channel("127.0.0.1:9098")
    client = test_pb2_grpc.GrpcServiceStub(channel=conn)
    respnse = client.hello(test_pb2.HelloRequest(data="xiao li"))
    print("received:",respnse.result)

if __name__ == '__main__':
    run()
  • 測試我們的結(jié)果,先啟動service.py服務(wù),然后執(zhí)行client.py,會直接返回
received: xiao li this is gprc test service

其他

這里只是一個簡單的grpc服務(wù)簡單,具體我們可以通過http的形式暴露成http的接口對外訪問,實(shí)際中要根據(jù)業(yè)務(wù)場景,對外提供不同的grpc服務(wù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容