22-基于Python构建GRPC服务
学习案例来源
https://zhuanlan.zhihu.com/p/97893141
安装包
pip install grpcio
pip install grpcio-tools
编写proto文件
syntax = "proto3";
service Cal {
rpc Add(AddRequest) returns (ResultReply) {}
rpc Multiply(MultiplyRequest) returns (ResultReply) {}
}
message AddRequest {
int32 num1 = 1;
int32 num2 = 2;
}
message MultiplyRequest {
int32 num1 = 1;
int32 num2 = 2;
}
message ResultReply {
int32 num = 1;
}
生成proto文件定义的类
python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. test.proto
ls
编写Server
from concurrent import futures
import grpc
import SimpleCal_pb2
import SimpleCal_pb2_grpc
class CalServicer(SimpleCal_pb2_grpc.CalServicer):
def Add(self, request, context):
print("Add function called")
return SimpleCal_pb2.ResultReply(num=request.num1+request.num2)
def Multiply(self, request, context):
print("Multiply function called")
return SimpleCal_pb2.ResultReply(num=request.num1*request.num2)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
SimpleCal_pb2_grpc.add_CalServicer_to_server(CalServicer(), server)
server.add_insecure_port("[::]:50051")
server.start()
print("grpc sercer start...")
server.wait_for_termination()
if __name__ == '__main__':
serve()
编写client
import SimpleCal_pb2
import SimpleCal_pb2_grpc
import grpc
def run(n, m):
channel = grpc.insecure_channel("localhost:50051") # 连接上grpc服务端
stub = SimpleCal_pb2_grpc.CalStub(channel)
response = stub.Add(SimpleCal_pb2.AddRequest(num1=n, num2=m))
print(f'{n} + {m} = {response}')
response2 = stub.Multiply(SimpleCal_pb2.MultiplyRequest(num1=n, num2=m))
print(f'{n} * {m} = {response2}')
if __name__ == '__main__':
for i in range(100):
run(2000, 304443)