标签:编译 add 格式 import int syn tools ice example
一:安装
pip install grpcio
pip install protobuf
pip install grpcio-tools
二:
1,定义grpc接口 message.proto
syntax = "proto3"; package example; #定义包的名称,这个名称server段和client端一模一样
service Message { #Message
rpc GetMessage(GetMessageRequest) returns (GetMessageResponse) {}
rpc ReadMessage(ReadRequest) returns (ReadResponse) {}
rpc SetUserToken(UserTokenRequest) returns (SetTokenResponse) {}
rpc GetUnreadMessageNumber(GetUnreadMessageNumberRequest) returns (GetUnreadMessageNumberResponse) {}
}
message GetMessageRequest { #定义client端传过来的数据格式以及名称
int32 global_user_id = 1;
int32 project_id = 2;
int32 page_number = 3;
int32 page_size = 4;
string token = 5;
}
2,编译protobuf:
python -m grpc_tools.protoc -I. –python_out=. –grpc_python_out=. ./message.proto
#在 example 目录中执行编译,会生成:
message_pb2.py 与message_pb2_grpc.py
3,client端操作
from __future__ import print_function
import grpc
from remote import message_pb2
from remote import message_pb2_grpc
def run(): with grpc.insecure_channel(‘测试服务器ip:3000‘) as channel: stub = message_pb2_grpc.MessageStub(channel) response = stub.GetMessage(message_pb2.GetMessageRequest(global_user_id=1, project_id=1, token="12ew", page_number=1, page_size=30)) print("client received : %s" % response)if __name__ == ‘__main__‘: run()
4,server端操作
from remote import message_pb2_grpc
from remote import message_pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class MessageServicer(message_pb2_grpc.MessageServicer):
def GetMessage(self, request, context):
"""
获取消息列表
"""
logger.info(request) #这里通过request.project_id等获取从client传过来的值,冰进行处理
result = check_token(request.project_id, request.token)
return message_pb2.GetMessageResponse(**result) #返回给client的值
def serve(): #这里定义一直等着接收消息
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
message_pb2_grpc.add_MessageServicer_to_server(MessageServicer(), server) #add_MessageServicer_to_server是自动生成的
server.add_insecure_port(‘[::]:3000‘)
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == ‘__main__‘:
serve()
ps:如果不能访问,查看下端口的权限是否放开,换个端口
标签:编译 add 格式 import int syn tools ice example
原文地址:https://www.cnblogs.com/52forjie/p/10075865.html