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

用 gRPC 实现 C ++ 的 RPC 通信,核心是三步:写好 .proto 接口定义、用 protoc 生成 C ++ 代码、在客户端和服务端分别实现 Stub 调用和 Service 逻辑。Protobuf 负责数据序列化,gRPC 负责网络传输和调用调度。
1. 定义服务接口(.proto 文件)
先创建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++ 免费学习笔记(深入)”;
2. 生成 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++。
3. 实现服务端
继承 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(); // 阻塞等待}
4. 实现客户端
用 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 通信就能跑起来。不复杂但容易忽略链接库和证书配置。