gRPC 是基于 HTTP/2 和 Protobuf 的高性能 RPC 框架,支持多语言,适用于低延迟、高吞吐的微服务通信。通过定义 .proto 文件声明服务接口和消息格式,使用 protoc 生成 C++ 代码,包含消息类和服务桩。服务端继承生成的服务类并实现 RPC 方法,如 SayHello 返回 “Hello, [name]”,并通过 ServerBuilder 启动监听。客户端使用存根(Stub)调用远程方法,通过 Channel 连接服务并处理响应。借助 CMake 配置编译,链接 gRPC 和 Protobuf 库,实现高效通信。关键在于掌握接口定义、代码生成与异步模型,适合性能敏感场景。

在现代分布式系统中,微服务之间需要高效、可靠的通信机制。gRPC 是 Google 开发的一个高性能、开源的远程过程调用(RPC)框架,支持多种语言,包括 C++。它基于 HTTP/2 协议,使用 Protocol Buffers(Protobuf)作为接口定义语言和数据序列化工具,非常适合构建低延迟、高吞吐量的服务间通信。
使用 gRPC 的第一步是定义服务接口和消息格式。你需要编写一个 .proto 文件来声明服务方法和传输的数据结构。
例如,创建一个 helloworld.proto 文件:
syntax = "proto3";
<p>package helloworld;</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>// 定义一个问候服务
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}</p><p>// 请求消息
message HelloRequest {
string name = 1;
}</p><p>// 响应消息
message HelloReply {
string message = 1;
}
这个文件定义了一个名为 Greeter 的服务,包含一个方法 SayHello,接收一个字符串参数并返回一条消息。
使用 Protobuf 编译器 protoc 和 gRPC 插件生成 C++ 代码。
安装依赖后,运行以下命令:
protoc --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto protoc --cpp_out=. helloworld.proto
这将生成四个文件:
继承生成的服务类,重写 RPC 方法。
示例服务实现:
#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"
<p>using grpc::Server;
using grpc::ServerBuilder;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;</p><p>class GreeterServiceImpl final : public Greeter::Service {
Status SayHello(ServerContext<em> context, const HelloRequest</em> request,
HelloReply* reply) override {
std::string prefix("Hello, ");
reply->set_message(prefix + request->name());
return Status::OK;
}
};</p><p>void RunServer() {
std::string server_address("0.0.0.0:50051");
GreeterServiceImpl service;</p><p>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();
}
该服务监听 50051 端口,收到请求时返回 “Hello, [name]”。
客户端通过存根(stub)调用远程服务。
#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"
<p>using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;</p><p>class GreeterClient {
public:
GreeterClient(std::shared<em>ptr<Channel> channel)
: stub</em>(Greeter::NewStub(channel)) {}</p><p>std::string SayHello(const std::string& user) {
HelloRequest request;
request.set_name(user);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">HelloReply reply;
ClientContext context;
Status status = stub_->SayHello(&context, request, &reply);
if (status.ok()) {
return reply.message();
} else {
std::cout << "RPC failed: " << status.error_code()
<< ": " << status.error_message() << std::endl;
return "RPC failed";
}}
private: std::uniqueptr<Greeter::Stub> stub; };
int main(int argc, char** argv) { GreeterClient client(grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials())); std::string user("world"); std::string reply = client.SayHello(user); std::cout << "Received: " << reply << std::endl; return 0; }
客户端连接本地服务,发送用户名并打印响应。
CMakeLists.txt 示例:
cmake_minimum_required(VERSION 3.14)
project(helloworld)
<p>find_package(Protobuf REQUIRED)
find_package(gRPC REQUIRED)</p><p>set(CMAKE_CXX_STANDARD 17)</p><p>add_executable(greeter_server server.cc helloworld.pb.cc helloworld.grpc.pb.cc)
add_executable(greeter_client client.cc helloworld.pb.cc helloworld.grpc.pb.cc)</p><p>target_link_libraries(greeter_server ${gRPC_LIBRARIES} ${PROTOBUF_LIBRARIES})
target_link_libraries(greeter_client ${gRPC_LIBRARIES} ${PROTOBUF_LIBRARIES})
target_include_directories(greeter_server PRIVATE ${gRPC_INCLUDE_DIRS} ${PROTOBUF_INCLUDE_DIRS})
target_include_directories(greeter_client PRIVATE ${gRPC_INCLUDE_DIRS} ${PROTOBUF_INCLUDE_DIRS})
确保正确链接 gRPC 和 Protobuf 库。
基本上就这些。C++ 结合 gRPC 可以实现高效的微服务通信,特别适合对性能要求高的场景。只要定义好接口,生成代码,再实现服务逻辑,就能快速搭建出稳定、高速的 RPC 服务。关键在于熟悉 .proto 定义和异步调用模型,后续可进一步探索流式 RPC 和认证机制。不复杂但容易忽略细节,比如版本兼容和线程安全。
以上就是C++如何使用gRPC进行微服务通信_C++实现高性能的远程过程调用(RPC)框架的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号