Python RPC 协议使用

一、文章介绍一下RPC中的一种grpc的使用案例

  1. 安装环境
    pip install grpcio
    pip install protobuf
    pip install grpcio_tools

二、编写协议文件(使用当中认为麻烦的一点)

//说明使用proto3语法定义协议
syntax = "proto3"; 

package compute;
//rpc在服务定义中定义方法,并指定其请求和响应类型,gRPC允许定义四种服务方法
service Compute {
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}

//服务方法中使用的所有请求和响应类型的协议缓冲区消息类型定义
message HelloRequest {
    string helloworld = 1;
}

message HelloReply {
    string result = 1;
}

三、根据协议文件生成python代码

$ python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/route_guide.proto

# python_out目录指定 xxxx_pb2.py的输出路径,我们指定为当前路径
# grpc_python_out指定xxxx_pb2_grpc.py文件的输出路径,我们指定为当前路径
# grpc_tools.protoc 这是我们刚刚安装的工具包
# -I参数指定协议文件的查找目录,我们都将它们设置为当前目录
# compute.proto 我们的协议文件

会生成以下文件

# compute_pb2.py       包含消息序列化类,用来和protobuf数据进行交互。 
# compute_pb2_grpc.py  包含服务器Stub类和客户端Stub类,以及待实现的服务RPC接口,用来和grpc进行交互

四、模拟服务端

import time
import grpc
from concurrent import futures
from RPC.grpc_test import compute_pb2, compute_pb2_grpc


class ComputeServicer(compute_pb2_grpc.ComputeServicer):
    def SayHello(self, request, ctx):
        max_len = str(len(request.helloworld))
        return compute_pb2.HelloReply(result=max_len)


def main():
    # 多线程服务器
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    servicer = ComputeServicer()
    # 注册本地服务,方法ComputeServicer只有这个是变的
    compute_pb2_grpc.add_ComputeServicer_to_server(servicer, server)
    # 监听端口
    server.add_insecure_port('127.0.0.1:19999')
    # 开始接收请求进行服务
    server.start()
    try:
        print("running...")
        time.sleep(1000)
    except KeyboardInterrupt:
        print("stopping...")
        server.stop(0)


if __name__ == '__main__':
    main()

五、模拟客户端

import grpc
from RPC.grpc_test import compute_pb2, compute_pb2_grpc

_HOST = '127.0.0.1'
_PORT = '19999'


def main():
    with grpc.insecure_channel("{0}:{1}".format(_HOST, _PORT)) as channel:
        client = compute_pb2_grpc.ComputeStub(channel=channel)
        response = client.SayHello(compute_pb2.HelloRequest(helloworld="zxc"))
    print("received: " + response.result)


if __name__ == '__main__':
    main()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容