python gRPC (1)

RPC基础

RPC 是两个子系统之间进行的直接消息交互,它使用操作系统提供的套接字来作为消息的载体,以特定的消息格式来定义消息内容和边界。

gRPC 是 Google 开源的基于 Protobuf 和 Http2.0 协议的通信框架,Google 深度学习框架 tensorflow 底层的 RPC 通信就完全依赖于 gRPC 库

gRPC的使用通常包括如下几个步骤:

  • 通过protobuf来定义接口和数据类型
  • 编写gRPC server端代码
  • 编写gRPC client端代码
    下面来通过一个实例来详细讲解上述的三步。

install response library:

pip install grpcio
pip install protobuf
pip install grpcio_tools

下边的hello world实例:

编写协议文件vim compute.proto

    syntax = "proto3"; //说明使用proto3语法定义协议
    package compute;
    service Compute {
        //我们rpc服务的名字
        // 服务端 会用到 <ComputeServicer>
        // 客户端 会用到 <ComputeStub>
        rpc SayHello (HelloRequest) returns (HelloReply) {}
        // SayHello 调用的方法
        // HelloRequest 客户端输入的消息(对象)
        // HelloReply 服务端 返回的消息(对象)
    }
    message HelloRequest {
        //定义 客户端输入消息内容
        string helloworld = 1;
    }

    message HelloReply {
        //定义服务端消息内容
        string result = 1;
    }

python -m grpc_tools.protoc -I ./ --python_out=./ --grpc_python_out=./ compute.proto

编写客户端

import grpc
import compute_pb2
import compute_pb2_grpc
_HOST = '127.0.0.1'
_PORT = '5000'
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="hello word"))
    print("received: " + response.result)
if __name__ == '__main__':
    main()

编写服务器

import time
import grpc
from concurrent import futures
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))
    # 实例化 计算len的类
    servicer = ComputeServicer()
    # 注册本地服务,方法ComputeServicer只有这个是变的
    compute_pb2_grpc.add_ComputeServicer_to_server(servicer, server)
    # 监听端口
    server.add_insecure_port('127.0.0.1:5000')
    # 开始接收请求进行服务
    server.start()
    try:
        print("serving  start...")
        time.sleep(1000)
    except KeyboardInterrupt:
        print("stopping...")
        server.stop(0)
if __name__ == '__main__':
    main()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值