C++用Thrift开发RPC需三步:写IDL定义接口、用thrift编译器生成C++代码、实现服务端逻辑与客户端调用;支持跨语言通信,依赖统一IDL、一致序列化及可配传输协议。

用 C++ 用 Thrift 做 RPC 开发,核心是三步:写 IDL 接口定义、用 thrift 编译器生成 C++ 代码、实现服务端逻辑和客户端调用。它天然支持跨语言(比如 Python/Java 客户端调用 C++ 服务),关键在于 IDL 统一、序列化一致、传输协议可配。
1. 安装 Thrift 并准备 IDL 文件
先确保系统有 thrift 编译器(v0.18+ 推荐):
- macOS:brew install thrift
- Ubuntu:apt install thrift-compiler
- 源码编译:从 thrift.apache.org 下载,configure + make + sudo make install
然后写一个 hello.thrift:
service HelloService {
string sayHello(1: string name),
}
2. 生成 C++ 服务骨架代码
运行命令生成 C++ 文件(含 server/client/stub):
立即学习“C++免费学习笔记(深入)”;
thrift -r --gen cpp hello.thrift
会生成 gen-cpp/ 目录,里面包含:
-
HelloService.h:接口声明与数据结构 -
HelloService.cpp:序列化/反序列化逻辑 -
HelloService_types.h:struct/enum 定义
注意:C++ 生成默认不带异步支持,如需异步需加 --gen cpp:async 参数(Thrift 0.17+)。
3. 实现服务端(单线程 + TSocket + TBinaryProtocol)
继承自生成的 HelloServiceIf 类,实现业务逻辑:
class HelloHandler : virtual public HelloServiceIf {
public:
void sayHello(std::string& _return, const std::string& name) override {
_return = "Hello, " + name + "!";
}
};
再启动一个简单服务器:
int main() {
auto handler = std::make_shared();
auto processor = std::make_shared(handler);
auto serverTransport = std::make_shared(9090);
auto transportFactory = std::make_shared();
auto protocolFactory = std::make_shared();
TSimpleServer server(processor, serverTransport,
transportFactory, protocolFactory);
server.serve();
return 0;
}
链接时加上:-lthrift -lpthread(Linux/macOS)。
4. 编写 C++ 客户端调用
客户端只需创建 socket、protocol、client 实例即可:
int main() {
boost::shared_ptr socket(new TSocket("localhost", 9090));
boost::shared_ptr transport(new TBufferedTransport(socket));
boost::shared_ptr protocol(new TBinaryProtocol(transport));
HelloServiceClient client(protocol);
transport->open();
std::string result;
client.sayHello(result, "World");
std::cout << result << std::endl; // 输出:Hello, World!
transport->close();
return 0;
}
注意:C++ 客户端依赖 boost::shared_ptr(Thrift 默认使用 Boost 智能指针),若用 C++11+ 且想换为 std::shared_ptr,需编译时加 --gen cpp:cxx11 参数,并链接 -lthriftcpp2(新版 libthriftcpp2 支持)。
5. 跨语言调用要点
只要 IDL 一致、协议匹配(如都用 TBinaryProtocol)、传输层兼容(TCP/HTTP),就能互通。例如:
- Python 客户端:用
thriftpip 包 + 同一份hello.thrift生成 py 代码,连同一 C++ 服务端 - Java 客户端:mvn 引入
org.apache.thrift:libthrift,生成 Java stub 后直连 9090 端口
常见坑:C++ 默认用 std::string,而 Python/Java 的字符串编码需统一为 UTF-8;结构体字段必须显式编号(避免兼容性断裂);服务重启后客户端需重连(无自动重试,需自行封装)。











