首先定义.proto文件描述服务接口和消息类型,使用protoc生成C++代码;接着实现服务端类并启动gRPC服务器;然后编写客户端通过stub调用远程方法;最后正确配置CMake链接gRPC和protobuf库完成编译。

在C++中使用gRPC进行远程过程调用(RPC),需要完成几个关键步骤:定义服务接口、生成代码、实现服务端和客户端逻辑,并通过protobuf与gRPC运行时通信。整个流程清晰,但涉及多个组件协同工作。
定义.proto文件并生成代码
gRPC依赖Protocol Buffers来定义服务接口和消息结构。你需要编写一个.proto文件,描述服务方法和传输的数据类型。
例如,创建helloworld.proto:
syntax = "proto3";
<p>package example;</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><p>message HelloRequest {
string name = 1;
}</p><p>message HelloResponse {
string message = 1;
}</p><p>service Greeter {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
使用protoc编译器配合gRPC插件生成C++代码:
protoc --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto
这会生成四个文件:helloworld.pb.cc、helloworld.pb.h、helloworld.grpc.pb.cc、helloworld.grpc.pb.h。这些是后续实现的基础。
实现服务端逻辑
服务端需要继承由gRPC生成的抽象服务类,并重写RPC方法。
定义服务类:
#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"
<p>class GreeterServiceImpl final : public example::Greeter::Service {
grpc::Status SayHello(grpc::ServerContext<em> context,
const example::HelloRequest</em> request,
example::HelloResponse* response) override {
response->set_message("Hello, " + request->name());
return grpc::Status::OK;
}
};
启动gRPC服务器:
void RunServer() {
std::string server_address("0.0.0.0:50051");
GreeterServiceImpl service;
<p>grpc::ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<grpc::Server> server = builder.BuildAndStart();
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
这里使用了InsecureServerCredentials(),适合本地测试。生产环境应使用TLS证书。
实现客户端调用
客户端通过存根(stub)发起远程调用。首先建立通道,再创建对应的存根实例。
#include "helloworld.grpc.pb.h"
#include <grpcpp/grpcpp.h>
<p>void SayHello(const std::string& user) {
grpc::ChannelArguments args;
std::shared_ptr<grpc::Channel> channel =
grpc::CreateCustomChannel("localhost:50051",
grpc::InsecureChannelCredentials(), args);</p><p>std::unique_ptr<example::Greeter::Stub> stub = example::Greeter::NewStub(channel);</p><p>example::HelloRequest request;
request.set_name(user);</p><p>example::HelloResponse response;
grpc::ClientContext context;</p><p>grpc::Status status = stub->SayHello(&context, request, &response);</p><p>if (status.ok()) {
std::cout << "Reply: " << response.message() << std::endl;
} else {
std::cout << "RPC failed: " << status.error_message() << std::endl;
}
}
调用SayHello("Alice")即可向服务端发送请求并接收响应。
编译与链接注意事项
使用CMake构建项目时,确保正确链接gRPC和protobuf库。
示例CMakeLists.txt片段:
find_package(Protobuf REQUIRED)
find_package(gRPC REQUIRED)
<p>add_executable(server server.cpp helloworld.pb.cc helloworld.grpc.pb.cc)
target_link_libraries(server ${gRPC_LIBRARIES} ${PROTOBUF_LIBRARIES})
target_include_directories(server PRIVATE ${gRPC_INCLUDE_DIRS} ${PROTOBUF_INCLUDE_DIRS})
确保系统已安装libgrpc++-dev、libprotobuf-dev等开发包。
基本上就这些。从定义接口到生成代码,再到实现服务端和客户端,gRPC在C++中的使用流程虽然涉及多个环节,但结构清晰,一旦熟悉后可以高效开发分布式服务。关键是理解.proto文件的作用以及如何与生成的类交互。不复杂但容易忽略细节,比如编译选项或依赖管理。











