reco.proto
syntax = "proto3"; package rpc_package; service HelloWorldService { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { repeated Student student=1; } message Student{ int32 age=1; string name=2; } message HelloReply { string message = 1; repeated int32 s_list=2; }
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. reco.proto
创建出 reco_pb2.py 和 reco_pb2_grpc.py 两个文件
然后写服务端代码
test_grpc_server.py
from concurrent import futures import grpc import logging import time from reco_pb2_grpc import add_HelloWorldServiceServicer_to_server, HelloWorldServiceServicer from reco_pb2 import HelloRequest, HelloReply class Hello(HelloWorldServiceServicer): # 这里实现我们定义的接口 def SayHello(self, request, context): s_list = [0,1,2,4,3] return HelloReply(message='Hello, {}! '.format(request.student),s_list=s_list) def serve(): # 这里通过thread pool来并发处理server的任务 server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # 将对应的任务处理函数添加到rpc server中 add_HelloWorldServiceServicer_to_server(Hello(), server) # 这里使用的非安全接口,世界gRPC支持TLS/SSL安全连接,以及各种鉴权机制 server.add_insecure_port('[::]:50000') server.start() try: while True: time.sleep(60 * 60 * 24) except KeyboardInterrupt: server.stop(0) if __name__ == "__main__": logging.basicConfig() serve()
test_grpc_client.py
from __future__ import print_function import logging import grpc from reco_pb2 import HelloRequest, HelloReply from reco_pb2_grpc import HelloWorldServiceStub def run(): # 使用with语法保证channel自动close with grpc.insecure_channel('localhost:50000') as channel: # 客户端通过stub来实现rpc通信 stub = HelloWorldServiceStub(channel) # 客户端必须使用定义好的类型,这里是HelloRequest类型 hellorequest = HelloRequest() for i in range(5): request = hellorequest.student.add() request.age = 18 request.name = "xinyuuliu" response = stub.SayHello(hellorequest) print ("hello client received: " + response.message) print(response.s_list) if __name__ == "__main__": logging.basicConfig() run()
结果:
hello client received: Hello, [age: 18 name: "xinyuuliu" , age: 18 name: "xinyuuliu" , age: 18 name: "xinyuuliu" , age: 18 name: "xinyuuliu" , age: 18 name: "xinyuuliu" ]! [0, 1, 2, 4, 3]