RPC基础
RPC 是两个子系统之间进行的直接消息交互,它使用操作系统提供的套接字来作为消息的载体,以特定的消息格式来定义消息内容和边界。
gRPC 是 Google 开源的基于 Protobuf 和 Http2.0 协议的通信框架,Google 深度学习框架 tensorflow 底层的 RPC 通信就完全依赖于 gRPC 库
基于python简单使用grpc
安装工具依赖
pip install grpcio
pip install protobuf
pip install grpcio_tools
编写协议文件vim compute.proto
syntax = "proto3"; //说明使用proto3语法定义协议
package compute;
service Compute {
// 我们rpc服务的名字
// 后面
// 服务端 会用到 <ComputeServicer>
// 客户端 会用到 <ComputeStub>
rpc SayHello (HelloRequest) returns (HelloReply) {}
// SayHello 调用的方法
// HelloRequest 客户端输入的消息(对象)
// returns 服务端
// HelloReply 服务端 返回的消息(对象)
}
message HelloRequest {
//定义 客户端输入消息内容
string helloworld = 1;
}
message HelloReply {
//定义服务端消息内容
string result = 1;
}
python -m grpc_tools.protoc -I ./ --python_out=./ --grpc_python_out=./ compute.proto
# python_out目录指定 xxxx_pb2.py的输出路径,我们指定为./ 当前路径
# grpc_python_out指定xxxx_pb2_grpc.py文件的输出路径,我们指定为./ 当前路径
# grpc_tools.protoc 这是我们的工具包,刚刚安装的
# -I参数指定协议文件的查找目录,我们都将它们设置为当前目录./
# compute.proto 我们的协议文件
ls
compute_pb2_grpc.py compute_pb2.py compute.proto
# compute.proto 协议文件
# compute_pb2.py 里面有消息序列化类
# compute_pb2_grpc.py 包含了服务器 Stub 类和客户端 Stub 类,以及待实现的服务 RPC 接口。
编写服务器
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:19999')
# 开始接收请求进行服务
server.start()
# 使用 ctrl+c 可以退出服务
try:
print("running...")
time.sleep(1000)
except KeyboardInterrupt:
print("stopping...")
server.stop(0)
if __name__ == '__main__':
main()
编写客户端
import grpc
import compute_pb2
import 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="123456"))
print("received: " + response.result)
if __name__ == '__main__':
main()