RPC 是两个子系统之间进行的直接消息交互,它使用操作系统提供的套接字来作为消息的载体,以特定的消息格式来定义消息内容和边界。
gRPC 是 Google 开源的基于 Protobuf 和 Http2.0 协议的通信框架,Google 深度学习框架 tensorflow 底层的 RPC 通信就完全依赖于 gRPC 库
编写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服务的名字
// 服务端 会用到
// 客户端 会用到
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()