• 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)
    
  • 相关阅读:
    springcloud的配置
    springboot面试题
    SqlServer取值四舍五入
    java导出Excel表格简单的方法
    pandas处理数据textrank提取关键词
    toarray()时出现memory error问题解决
    回溯法解决N皇后问题 C语言
    图论中四个最短路径算法
    第一个java程序
    js 实现简单屏蔽某个地区的访问
  • 原文地址:https://www.cnblogs.com/lotuslaw/p/15200450.html
Copyright © 2020-2023  润新知