在 gRPC 客户端代码中,stub_
是通过 gRPC 生成的客户端存根(Stub)对象,用于调用远程服务。以下是详细解释:
1. stub_
的来源
stub_
是通过 gRPC 工具根据.proto
文件中的服务定义自动生成的客户端存根类(例如ExampleService::Stub
)的实例。- 通常通过以下方式创建:
// 创建通道(Channel)连接到服务端 auto channel = grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()); // 通过通道创建存根实例 stub_ = ExampleService::NewStub(channel);
stub_
封装了网络通信细节,提供了与服务端方法对应的本地方法(如Add
),使得远程调用看起来像本地调用。
2. Add
方法的三个参数
(1)grpc::ClientContext* context
- 作用:用于传递调用的上下文信息(如超时设置、元数据(metadata)、认证凭证等)。
- 示例用法:
grpc::ClientContext context; context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(5)); // 设置超时 context.AddMetadata("key", "value"); // 添加自定义元数据
- 注意:每次调用都需要创建一个新的
ClientContext
对象(不可复用)。
(2)AddRequest* request
- 作用:包含需要发送给服务端的请求数据(即输入参数)。其结构由
.proto
文件中的message AddRequest
定义。 - 示例: “`proto message AddRequest { int32 a = 1; int32 b = 2; }
这里request.set_a(5)和request.set_b(3)就是填充请求消息。
(3)AddResponse response*
- 作用:用于接收服务端返回的响应数据(即计算结果)。其结构由.proto文件中的message AddResponse定义。
- 示例:
message AddResponse {
int32 result =1;}
###3.调用过程说明 1.客户端通过stub_->Add(…)发起RPC调用,将request序列化并通过网络发送到服务端。 2.客户端等待服务端响应(同步调用),或使用异步接口处理响应(异步调用)。 3.服务端处理请求后,将结果填充到response中并返回给客户端。 4.客户端从response中提取结果(如response.result())。
###4.完整示例代码框架
// 创建通道和存根
auto channel = grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials());
std::unique_ptr<ExampleService::Stub> stub_ = ExampleService::NewStub(channel);
// 准备请求和上下文
AddRequest request;
request.set_a(5);
request.set_b(3);
AddResponse response;
grpc::ClientContext context;
// 发起同步调用
grpc::Status status = stub_->Add(&context, request, &response);
if (status.ok()) {
std::cout << "Result: " << response.result(); //输出8
} else {
std::cout << "RPC failed: " << status.error_message();
}
###5.其他注意事项 -如果使用异步调用,需额外处理完成队列(CompletionQueue)和状态回调。 -stub_的方法通常是线程安全的,但ClientContext非线程安全(每次调用需独立创建)。 -通过.proto文件中的rpc Add(AddRequest) returns (AddResponse);定义生成此方法。
总结:stub_是gRPC生成的客户端存根,负责网络通信;Add的三个参数分别控制调用上下文、输入请求和输出响应。
内容由零声教学AI助手提供,问题来源于学员提问