在 gRPC 中,可以通过设置超时时间来控制回复的超时。以下是一个示例:
#include <grpcpp/grpcpp.h>
void MyFunction() {
// 创建 Channel 和 Stub
std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials());
std::unique_ptr<MyService::Stub> stub = MyService::NewStub(channel);
// 创建请求消息
MyRequest request;
request.set_data("Hello");
// 设置调用选项
grpc::ClientContext context;
// 设置超时时间为5秒钟
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::seconds(5);
context.set_deadline(deadline);
// 发起 RPC 调用
grpc::Status status = stub->MyMethod(&context, request, &response);
if (status.ok()) {
// 处理响应结果
std::cout << "Response: " << response.message() << std::endl;
} else {
// 处理错误情况
std::cout << "RPC Error: " << status.error_message() << std::endl;
}
}
在上面的代码中,set_deadline() 方法被用于设置调用的超时时间。你可以根据需要自定义超时值。
内容由零声教学AI助手提供,问题来源于学员提问




