gRPC实现C++ RPC通信需三步:定义.proto接口、用protoc生成C++代码(含消息类和Stub/Service)、在服务端继承Service实现方法、客户端调用Stub。

用gRPC实现C++的RPC通信,核心是三步:写好.proto接口定义、用protoc生成C++代码、在客户端和服务端分别实现Stub调用和Service逻辑。Protobuf负责数据序列化,gRPC负责网络传输和调用调度。
先创建helloworld.proto,声明服务方法和消息结构:
syntax = "proto3";
<p>package helloworld;</p><p>// 请求和响应消息
message HelloRequest {
string name = 1;
}</p><p>message HelloReply {
string message = 1;
}</p><p>// RPC服务
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply) {}
}注意:syntax = "proto3"是必须的;package影响生成的C++命名空间;每个字段要有唯一数字标签。
立即学习“C++免费学习笔记(深入)”;
安装gRPC和protobuf后,运行以下命令生成头文件和源码:
protoc -I . --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto
会生成两个文件:
helloworld.pb.h / helloworld.pb.cc:含消息类(如HelloRequest)helloworld.grpc.pb.h / helloworld.grpc.pb.cc:含Stub类(Greeter::Stub)和服务基类(Greeter::Service)编译时需链接libprotobuf、libgrpc、libgrpc++。
继承Greeter::Service,重写SayHello方法,用ServerContext控制生命周期:
class GreeterServiceImpl final : public helloworld::Greeter::Service {
public:
Status SayHello(ServerContext* context, const helloworld::HelloRequest* request,
helloworld::HelloReply* reply) override {
std::string prefix("Hello ");
reply->set_message(prefix + request->name());
return Status::OK;
}
};启动服务器示例:
void RunServer() {
std::string server_address("0.0.0.0:50051");
GreeterServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait(); // 阻塞等待
}用Greeter::NewStub()创建Stub,发起同步或异步调用:
int main() {
std::string target_str = "localhost:50051";
auto channel = grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials());
auto stub = helloworld::Greeter::NewStub(channel);
<p>helloworld::HelloRequest request;
request.set_name("World");</p><p>helloworld::HelloReply reply;
ClientContext context;
Status status = stub->SayHello(&context, request, &reply);</p><p>if (status.ok()) {
std::cout << reply.message() << std::endl;
} else {
std::cout << "RPC failed: " << status.error_message() << std::endl;
}
return 0;
}关键点:
ClientContext可设置超时、自定义元数据Status;异步调用需配合CompletionQueue
grpc::InsecureChannelCredentials()用于本地测试,生产环境应改用TLS凭证基本上就这些。只要.proto定义清晰、生成步骤正确、服务/客户端按规范实现,C++ gRPC通信就能跑起来。不复杂但容易忽略链接库和证书配置。
以上就是C++如何使用gRPC实现RPC通信?(Protobuf示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号