grpc 安裝與簡單測試-python語言

1、gRPC 的安裝:
    $ pip install grpcio
    
2、安裝 ProtoBuf 相關的 python 依賴庫:
    $ pip install protobuf

3、安裝 python grpc 的 protobuf 編譯工具:
    $ pip install grpcio-tools


4、創建定義的文件 helloworld.proto 內容如下:
    syntax = "proto3";
    // The greeting service definition.
    service Greeter {
      // Sends a greeting
      rpc say_hello (HelloRequest) returns (HelloReply) {}
    }
    
    // The request message containing the user's name.
    message HelloRequest {
      string name = 1;
    }
    
    // The response message containing the greetings
    message HelloReply {
      string message = 1;
    }
    

5、編譯服務器和客戶端文件
    python -m grpc_tools.protoc -I ./  --python_out=. --grpc_python_out=.  ./helloworld.proto
    
    當前目錄下生成
    helloworld_pb2_grpc.py
    helloworld_pb2.py
    
    
6、創建服務端文件 greeter_server.py
    # Copyright 2015 gRPC authors.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    """The Python implementation of the GRPC helloworld.Greeter server."""
    
    from concurrent import futures
    import time
    import logging
    
    import grpc
    
    import helloworld_pb2
    import helloworld_pb2_grpc
    
    _ONE_DAY_IN_SECONDS = 60 * 60 * 24
    
    
    class Greeter(helloworld_pb2_grpc.GreeterServicer):
    
        def say_hello(self, request, context):
            return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
    
    
    def serve():
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), 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__':
        logging.basicConfig()
        serve()
    
7、創建客戶端文件  greeter_client.py 
    # Copyright 2015 gRPC authors.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    """The Python implementation of the GRPC helloworld.Greeter client."""

    from __future__ import print_function
    import logging

    import grpc

    import helloworld_pb2
    import helloworld_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 = helloworld_pb2_grpc.GreeterStub(channel)
            response = stub.say_hello(helloworld_pb2.HelloRequest(name='pwp'))
        print("Greeter client received: " + response.message)


    if __name__ == '__main__':
        logging.basicConfig()
        run()

8、運行服務端 
    python greeter_server.py
    
    
9、運行客戶端調用
    python greeter_client.py 
    打印:
    Greeter client received: Hello, pwp!
    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章