Apache Thrift 是一款跨語言的 RPC 框架,透過定義中介介面描述語言(IDL)檔案,自動生成多語言的客戶端與服務端代碼。本文以 C++ 為例,完整演示從 .thrift 定義到編譯、運行的全流程。
建立 worker.thrift,定義一個簡單的 WorkerManager 服務,提供 ping() 方法供客戶端探活:
// worker.thrift
namespace cpp freebird
service WorkerManager {
void ping()
}
使用 Thrift 編譯器生成代碼:
thrift -r --gen cpp -o ../ worker.thrift
生成目錄結構:
gen-cpp/ ├── worker_constants.cpp/h ├── WorkerManager.cpp/h ├── WorkerManager_server.skeleton.cpp ← 服務端骨架 ├── worker_types.cpp/h
複製 WorkerManager_server.skeleton.cpp 並填入業務邏輯:
#include "WorkerManager.h" #include#include #include #include using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::server; using namespace freebird; class WorkerManagerHandler : virtual public WorkerManagerIf { public: void ping() override { printf("ping\n"); // 實際業務邏輯 } }; int main() { int port = 9090; auto handler = std::make_shared (); auto processor = std::make_shared ; auto serverTransport = std::make_shared (port); auto transportFactory = std::make_shared (); auto protocolFactory = std::make_shared (); TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); server.serve(); return 0; }
#include#include #include #include #include "WorkerManager.h" using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace freebird; int main() { auto socket = make_shared ("localhost", 9090); auto transport = make_shared (socket); auto protocol = make_shared (transport); WorkerManagerClient client(protocol); try { transport->open(); client.ping(); cout << "ping() succeeded" << endl; transport->close(); } catch (TException& tx) { cout << "ERROR: " << tx.what() << endl; } return 0; }
thrift_base/
├── client/
│ ├── builder/ # 編譯腳本
│ ├── include/
│ └── src/main.cc # 客戶端代碼
└── server/
├── builder/ # 編譯腳本
├── gen-cpp/ # 生成代碼
└── thrift/worker.thrift
編譯命令(需配合專案自帶的 rebuild.lsp 與 debug_config.lsp):
cd builder && ./rebuild.lsp debug_config.lsp
./thrift_server(監聽 9090 端口)./thrift_clientping,客戶端顯示成功訊息TSimpleServer 為單執行緒阻塞模型,適合管理類介面,不適合高併發數據傳輸TThreadPoolServer 或 TNonblockingServernamespace cpp freebird 決定生成代碼的 C++ 命名空間