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";package helloworld;
// 请求和响应消息 message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }
// 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(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);
helloworld::HelloRequest request;
request.set_name("World");
helloworld::HelloReply reply;
ClientContext context;
Status status = stub->SayHello(&context, request, &reply);
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通信就能跑起来。不复杂但容易忽略链接库和证书配置。










