当前位置:首页 > C++ > 正文

gRPC快速上手(C++语言开发实战指南)

在现代微服务架构中,gRPC 已经成为高性能、跨语言通信的首选方案之一。如果你是 C++ 开发者,并希望了解如何使用 gRPC 构建高效的服务端与客户端程序,那么这篇 gRPC C++教程 将带你从零开始搭建一个完整的 gRPC 应用。

什么是 gRPC?

gRPC 是由 Google 开源的一个高性能、开源、通用的 RPC(远程过程调用)框架。它基于 HTTP/2 协议传输,使用 Protocol Buffers(简称 Protobuf)作为接口定义语言(IDL)和底层消息交换格式。gRPC 支持多种语言,包括 C++、Java、Python、Go 等。

gRPC快速上手(C++语言开发实战指南) gRPC C++教程  gRPC入门指南 C++ gRPC示例 gRPC通信协议 第1张

为什么选择 gRPC?

  • 高性能:基于 HTTP/2 和二进制编码(Protobuf),比 JSON + REST 更快更小。
  • 强类型接口:通过 .proto 文件定义服务和消息,自动生成客户端和服务端代码。
  • 跨语言支持:一次定义,多语言实现。
  • 支持多种通信模式:单向 RPC、服务器流、客户端流、双向流。

准备工作

在开始之前,请确保你的系统已安装以下工具:

  • CMake(≥ 3.13)
  • g++ 或 clang(支持 C++11 以上)
  • Git
  • Protobuf 编译器(protoc)
  • gRPC C++ 库

你可以通过以下命令在 Ubuntu 上安装依赖(其他系统请参考官方文档):

sudo apt updatesudo apt install -y build-essential autoconf libtool pkg-config# 安装 Protobufgit clone https://github.com/protocolbuffers/protobuf.gitcd protobuf./autogen.sh./configuremake -j$(nproc)sudo make installsudo ldconfigcd ..# 安装 gRPCgit clone --recurse-submodules -b v1.54.0 https://github.com/grpc/grpccd grpcmkdir -p cmake/buildcd cmake/buildcmake ../..make -j$(nproc)sudo make installsudo ldconfig

第一步:定义 .proto 接口文件

我们创建一个简单的“问候服务”(Greeter Service)。新建文件 helloworld.proto

syntax = "proto3";package helloworld;// 定义服务service Greeter {  // 一个简单的 RPC 方法:接收 HelloRequest,返回 HelloReply  rpc SayHello (HelloRequest) returns (HelloResponse);}// 请求消息message HelloRequest {  string name = 1;}// 响应消息message HelloResponse {  string message = 1;}

这个文件定义了一个名为 Greeter 的服务,包含一个叫 SayHello 的方法。请求和响应分别由 HelloRequestHelloResponse 消息结构体定义。

第二步:生成 C++ 代码

使用 protoc 编译器和 gRPC 插件生成 C++ 代码:

protoc --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto

执行后会生成四个文件:

  • helloworld.pb.h / helloworld.pb.cc:Protobuf 消息类
  • helloworld.grpc.pb.h / helloworld.grpc.pb.cc:gRPC 服务类

第三步:编写服务端代码

创建 greeter_server.cc

#include <iostream>#include <memory>#include <string>#include <grpcpp/grpcpp.h>#include "helloworld.grpc.pb.h"using grpc::Server;using grpc::ServerBuilder;using grpc::ServerContext;using grpc::Status;using helloworld::Greeter;using helloworld::HelloRequest;using helloworld::HelloResponse;class GreeterServiceImpl final : public Greeter::Service {  Status SayHello(ServerContext* context, const HelloRequest* request,                  HelloResponse* 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();}int main(int argc, char** argv) {  RunServer();  return 0;}

第四步:编写客户端代码

创建 greeter_client.cc

#include <iostream>#include <memory>#include <string>#include <grpcpp/grpcpp.h>#include "helloworld.grpc.pb.h"using grpc::Channel;using grpc::ClientContext;using grpc::Status;using helloworld::Greeter;using helloworld::HelloRequest;using helloworld::HelloResponse;class GreeterClient { public:  GreeterClient(std::shared_ptr<Channel> channel)      : stub_(Greeter::NewStub(channel)) {}  std::string SayHello(const std::string& user) {    HelloRequest request;    request.set_name(user);    HelloResponse reply;    ClientContext context;    Status status = stub_->SayHello(&context, request, &reply);    if (status.ok()) {      return reply.message();    } else {      std::cout << "RPC failed" << std::endl;      return "RPC failed";    }  } private:  std::unique_ptr<Greeter::Stub> stub_;};int main(int argc, char** argv) {  GreeterClient greeter(grpc::CreateChannel(      "localhost:50051", grpc::InsecureChannelCredentials()));  std::string user("world");  std::string reply = greeter.SayHello(user);  std::cout << "Greeter received: " << reply << std::endl;  return 0;}

第五步:编译并运行

使用以下 CMakeLists.txt 文件进行编译:

cmake_minimum_required(VERSION 3.13)project(greeter_example LANGUAGES CXX)find_package(PkgConfig REQUIRED)find_package(Threads REQUIRED)# Find gRPC and Protobuffind_package(gRPC CONFIG REQUIRED)find_package(Protobuf CONFIG REQUIRED)# Generate proto files (optional if already generated)# set(PROTO_FILE ${CMAKE_CURRENT_SOURCE_DIR}/helloworld.proto)# protobuf_generate(TARGET greeter_proto LANGUAGE cpp PROTOS ${PROTO_FILE})# protobuf_generate(TARGET greeter_grpc LANGUAGE grpc GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc PROTOS ${PROTO_FILE})add_executable(greeter_server greeter_server.cc helloworld.pb.cc helloworld.grpc.pb.cc)target_link_libraries(greeter_server gRPC::grpc++ gRPC::grpc++_reflection)target_include_directories(greeter_server PRIVATE ${CMAKE_CURRENT_BINARY_DIR})add_executable(greeter_client greeter_client.cc helloworld.pb.cc helloworld.grpc.pb.cc)target_link_libraries(greeter_client gRPC::grpc++)target_include_directories(greeter_client PRIVATE ${CMAKE_CURRENT_BINARY_DIR})

然后执行编译:

mkdir build && cd buildcmake ..make -j

启动服务端:

./greeter_server

在另一个终端运行客户端:

./greeter_client

你将看到输出:

Greeter received: Hello world

总结

通过本篇 gRPC入门指南,你已经掌握了如何在 C++ 中使用 gRPC 构建一个简单的客户端-服务端通信系统。从定义 .proto 文件到生成代码、编写逻辑、编译运行,每一步都清晰明了。

后续你可以尝试扩展功能,比如添加流式 RPC、使用 TLS 加密通信、集成到现有项目等。gRPC 的强大之处在于其灵活性和性能,非常适合构建现代分布式系统。

希望这篇 C++ gRPC示例 教程对你有帮助!如果你正在学习微服务或需要高效的内部通信机制,gRPC通信协议 绝对值得深入研究。