1.需要下载的包
pip install grpcio
pip install grpcio-tools
pip install protobuf为了更好的书写proto文件,你可以在pycharm下载第三插件Protocol Buffers
2.编写proto文件: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;
}
3.生产GRPC代码:compute_pb2_grpc.py ,compute_pb2.py
import os
if __name__ == '__main__':
file_out = "python -m grpc_tools.protoc -I ./ --python_out=./ --grpc_python_out=./ compute.proto"
os.popen(file_out, mode='r')
# 新接口第一次需要运行这个文件
# python_out目录指定 xxxx_pb2.py的输出路径,我们指定为./ 当前路径
# grpc_python_out指定xxxx_pb2_grpc.py文件的输出路径,我们指定为./ 当前路径
# grpc_tools.protoc 这是我们的工具包,刚刚安装的
# -I参数指定协议文件的查找目录,我们都将它们设置为当前目录./
# compute.proto 我们的协议文件
# 会生成compute_pb2_grpc.py compute_pb2.py两个文件
# compute.proto 协议文件
# compute_pb2.py 里面有消息序列化类
# compute_pb2_grpc.py 包含了服务器 Stub 类和客户端 Stub 类,以及待实现的服务 RPC 接口。
4.编写服务端启动文件:ComputeServicer.py
import time
from concurrent import futures
import grpc
# 刚刚生产的两个文件
import compute_pb2
import 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...")
# 启动后多少秒自动关闭服务,如果想保持服务进程用:server.wait_for_termination()
time.sleep(10)
except KeyboardInterrupt:
print("stopping...")
server.stop(0)
if __name__ == '__main__':
main()5.编写python远程调用文件:client.py
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="1234567"))
print("received: " + response.result)
if __name__ == '__main__':
main()6.操作注意需要先启动服务端ComputeServicer.py,再用client.py去调用。使用proto文件生成的时候,需要注意生成文件内代码块的路径问题(正常运行以上代码是无路径问题)
版权声明:本文为qq_41407617原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。