测试 gRPC 调用
要测试 gRPC 调用,我们可以使用 Python 脚本与 gRPC 服务进行通信。下面是两个示例 Python 脚本,分别在 A 节点 和 B 节点 上运行。A 节点通过 gRPC 调用 B 节点的接口。
1. 在 B 节点上启动 gRPC 服务
首先,我们需要在 B 节点上启动一个简单的 gRPC 服务,供 A 节点进行调用。假设服务是一个简单的 RPC,返回一些文本数据。
B 节点的 gRPC 服务(server.py)
import grpc
from concurrent import futures
import time# 导入自动生成的文件,假设我们用 proto 文件定义了接口
import hello_pb2
import hello_pb2_grpc# 定义 gRPC 服务类
class Greeter(hello_pb2_grpc.GreeterServicer):def SayHello(self, request, context):return hello_pb2.HelloReply(message='Hello, ' + request.name)def serve():server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)server.add_insecure_port('[::]:50051') # 监听 50051 端口server.start()print("gRPC server started on port 50051")try:while True:time.sleep(86400) # 让服务一直运行except KeyboardInterrupt:server.stop(0)if __name__ == '__main__':serve()
2. 在 A 节点上调用 B 节点的 gRPC 服务
接下来,我们在 A 节点上编写一个脚本,通过 gRPC 客户端调用 B 节点的接口。
A 节点的 gRPC 客户端(client.py)
import grpc
import hello_pb2
import hello_pb2_grpcdef run():# 连接到 B 节点的 gRPC 服务channel = grpc.insecure_channel('B_NODE_IP:50051') # B_NODE_IP 替换为 B 节点的 IP 地址stub = hello_pb2_grpc.GreeterStub(channel)# 构造请求request = hello_pb2.HelloRequest(name='A Node')# 调用 gRPC 服务response = stub.SayHello(request)# 输出 B 节点返回的数据print(f"Response from B node: {response.message}")if __name__ == '__main__':run()
3. 创建 .proto 文件
为了使用 gRPC,你需要使用 Protocol Buffers 来定义接口和消息。我们创建一个 .proto
文件来定义请求和响应格式。
hello.proto
syntax = "proto3";package hello;// 定义请求消息
message HelloRequest {string name = 1;
}// 定义响应消息
message HelloReply {string message = 1;
}// 定义 Greeter 服务
service Greeter {rpc SayHello (HelloRequest) returns (HelloReply);
}
4. 编译 .proto 文件
使用 protoc
编译 .proto
文件,生成 Python 代码。运行以下命令:
python3 -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. hello.proto
这会生成 hello_pb2.py
和 hello_pb2_grpc.py
文件,它们会被 server.py
和 client.py
引用。
5. 运行服务和客户端
-
在 B 节点上启动 gRPC 服务:
python3 server.py
-
在 A 节点上运行 gRPC 客户端:
python3 client.py
注意事项:
-
确保 A 节点 可以访问 B 节点 的 IP 地址和端口
50051
。 -
如果两者在不同的网络中,可能需要配置防火墙或路由设置,确保网络连接通畅。
-
确保安装了所需的 gRPC 库:
pip install grpcio grpcio-tools
。
这样,A 节点的客户端就可以通过 gRPC 向 B 节点发送请求,B 节点会响应结果并返回给 A 节点。
附部分命令:
python3 -m venv myenv
source myenv/bin/activate
pip install grpcio-tools -i https://pypi.tuna.tsinghua.edu.cn/simple