GRPC Hello World(Python版)

一、前言

假定已对protobuf的语法有了一定的了解,若无,需自行学习。

需要已经完成protoc的安装。

本文基本参考gRPC官方文档,作为学习过程的记录。

二、参考

Protobuf Google官方文档https://developers.google.com/protocol-buffers/docs/overview)

Google官方文档https://grpc.io/docs/

gRPC 官方文档中文版https://doc.oschina.net/grpc?t=56831

三、Python

环境搭建

  1. 官方Github链接https://github.com/grpc/grpc.git
    本地git clone或直接下载
    git clone https://github.com/grpc/grpc.git
  2. 相关库安装
    pip install grpcio grpcio-tools protobuf
    若失败,可能与pip版本有关
    完成后可以运行已经写好的例程进行检验,目录为grpc-master/examples/python/helloworld,先运行服务器端
    python greeter_server.py
    新开一个终端运行客服端
    python greeter_client.py
    即可看到输出Greeter client received: Hello, you!
    该目录下的helloworld_pb2.py和helloworld_pb2_grpc.py即为proto文件编译后所产生。
  3. 编译grpc-python插件
    在grpc主目录下执行
    make grpc_python_plugin
    编译成功后会提醒生成到/grpc-master/bins/opt/grpc_python_plugin

四、Hello World

proto文件

grpc-master/examples/protos/ 目录下,有4个官方例程,其中helloworld.proto主要包括三个部分:

HelloRequest与HelloResponse定义请求和回复的数据结构,均仅包含一个字符串。

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

Greeter如注释所说,就是定义的服务,即给SayHello方法传入HelloRequest会返回HelloReply。

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

编译proto

作为示例,在grpc-master/examples/protos/ 目录中新建了一个tmp目录,已将grpc_python_plugin拷入该目录中。

在grpc-master/examples/protos/下执行

protoc -I . –python_out=tmp –grpc_out=tmp –plugin=protoc-gen-grpc=tmp/grpc_python_plugin helloworld.proto

参数的解释参阅protobuf的相关文档,此处不赘述

即可看到tmp目录下已经生成了所需的helloworld_pb2.py和helloworld_pb2_grpc.py

服务器端(TODO)

class Greeter(helloworld_pb2_grpc.GreeterServicer):

    def SayHello(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)

客户端(TODO)

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.SayHello(helloworld_pb2.HelloRequest(name='you'))
    print("Greeter client received: " + response.message)

你可能感兴趣的:(GRPC)