grpc例子
什么是RPC
RPC(Remote Procedure Call Protocol)-- 遠程過程調用協議,它是一種通過網絡從遠程計算機程序上請求服務,而不需要了解底層網絡協議的協議。RPC協議假定某些傳輸協議的存在,如TCP或UDP,為通信程序之間攜帶信息數據。在OSI網絡通信模型中,RPC跨越了傳輸層和應用層。RPC使得開發包括網絡分布式多程序在內的應用程序更加容易。?
什么是gRPC
gRPC 是Google開源的一款高性能的 RPC 框架,它基于 ProtoBuf 序列化協議進行開發,支持多種開發語言(Golang、Python、Java、C/C++等)。gRPC 提供了一種簡單的方法來定義服務,同時客戶端可以充分利用 HTTP/2 stream 的特性,從而有助于節省帶寬、降低 TCP 的連接次數、節省CPU的使用等。?
本文參考官方文檔[grpc.html],以及gRPC的GitHub開源項目grpc/grpc。并通過一個小demo展示框架用法。
安裝gRPC及gRPC工具
pip install grpcio pip install grpcio-toolsgrpcio-tools包含了protobuf的編輯工具 protoc,用來根據 .proto 服務定義生成服務器端和客戶端代碼。
?
自定義 gRPC 接口
假定這里我們需要定義一個數據接收服務Receiver,用來接收客戶端傳遞給服務器端的數據。
syntax = "proto3"; import "google/protobuf/struct.proto";// 服務定義 service Receiver {rpc receive (Event) returns (Reply) {} }// 接收消息定義 message Event {string appid = 1;int32 xwhen = 2;string xwho = 3;string xwhat = 4;google.protobuf.Struct xcontext = 5; }// 返回消息定義 message Reply {int32 status = 1;string message = 2; }?
編譯 proto 文件生成服務接口
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./receiver.proto這里會生成兩個python文件:
receiver_pb2.py receiver_pb2_grpc.py?
編寫Server端代碼
# _*_ coding: utf-8 _*_import grpc import receiver_pb2 import receiver_pb2_grpcimport time from concurrent import futures_ONE_DAY_IN_SECONDS = 60 * 60 * 24class Receiver(receiver_pb2_grpc.ReceiverServicer):# 重寫父類方法,返回消息def receive(self, request, context):print('request:', request)return receiver_pb2.Reply(message='Hello, %s!' % request.xwho)if __name__ == '__main__':server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))receiver_pb2_grpc.add_ReceiverServicer_to_server(Receiver(), server)server.add_insecure_port('[::]:50051')server.start()print('server start...')try:while True:time.sleep(_ONE_DAY_IN_SECONDS)except KeyboardInterrupt:server.stop(0)?
編寫client端代碼
# _*_ coding: utf-8 _*_import grpc import receiver_pb2 import receiver_pb2_grpc from google.protobuf import struct_pb2def run():channel = grpc.insecure_channel('localhost:50051')stub = receiver_pb2_grpc.ReceiverStub(channel)# 自定義struct結構struct = struct_pb2.Struct()struct['idfa'] = 'idfa1'struct['amount'] = 123response = stub.receive(receiver_pb2.Event(xwhat='install', appid='fuckgod', xwhen=123, xwho='jerry', xcontext=struct))print("client status: %s received: %s" % (response.status, response.message))if __name__ == '__main__':run()?
測試流程
(1)啟動server:python?server.py?&
(2)運行client.py發送消息
server輸出:
server start... request: appid: "fuckgod" xwhen: 123 xwho: "jerry" xwhat: "install" xcontext {fields {key: "amount"value {number_value: 123.0}}fields {key: "idfa"value {string_value: "idfa1"}} }client輸出:
client status: 0 received: Hello, jerry!表示測試成功。
轉載自https://zhuanlan.zhihu.com/p/37158888
總結
- 上一篇: 【Jmeter篇】1小时轻松搞定项目接口
- 下一篇: Django在根据models生成数据库