grpc python的使用与golang交互
python 安装grpc
pip install grpcio
pip install grpcio-tools googleapis-common-protos
使用:
新建一个 msg.proto 文件。
syntax = "proto3";
service MsgService {
rpc GetMsg (MsgRequest) returns (MsgResponse){}
}
message MsgRequest {
string name = 1;
}
message MsgResponse {
string msg = 1;
}
生成接口代码
python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=. msg.proto
就会看到两个py文件: msg_pb2.py
和 msg_pb2_grpc.py
python grpc 创建服务端
import grpc
import msg_pb2
import msg_pb2_grpc
from concurrent import futures
import time
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class MsgServicer(msg_pb2_grpc.MsgServiceServicer):
def GetMsg(self, request, context):
print("Received name: %s" % request.name)
return msg_pb2.MsgResponse(msg='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
msg_pb2_grpc.add_MsgServiceServicer_to_server(MsgServicer(), server)
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
python 创建客户端
import grpc
import msg_pb2
import msg_pb2_grpc
def run():
# NOTE(gRPC Python Team): .close() is possible on a channel and should be
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = msg_pb2_grpc.MsgServiceStub(channel)
response = stub.GetMsg(msg_pb2.MsgRequest(name='world'))
print("Client received: " + response.msg)
if __name__ == '__main__':
run()
与golang交互
python 可以通过grpc与golang交互, 推拉数据; 注意的是需要维护好 proto文件;