首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 實現 Thrift RPC 入門:從 IDL 定義到客戶端/服務端完整範例

     編輯:關於C++

概述

Apache Thrift 是一款跨語言的 RPC 框架,透過定義中介介面描述語言(IDL)檔案,自動生成多語言的客戶端與服務端代碼。本文以 C++ 為例,完整演示從 .thrift 定義到編譯、運行的全流程。

1. 定義 Thrift IDL 檔案

建立 worker.thrift,定義一個簡單的 WorkerManager 服務,提供 ping() 方法供客戶端探活:

// worker.thrift
namespace cpp freebird

service WorkerManager {
    void ping()
}

2. 生成 C++ 代碼

使用 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

3. 實現服務端邏輯

複製 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;
}

4. 編寫客戶端代碼

#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;
}

5. 專案目錄與編譯

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

6. 運行驗證

  1. 啟動服務端:./thrift_server(監聽 9090 端口)
  2. 啟動客戶端:./thrift_client
  3. 觀察服務端控制台輸出 ping,客戶端顯示成功訊息

關鍵點總結

  • TSimpleServer 為單執行緒阻塞模型,適合管理類介面,不適合高併發數據傳輸
  • 生產環境建議使用 TThreadPoolServer 或 TNonblockingServer
  • IDL 中的 namespace cpp freebird 決定生成代碼的 C++ 命名空間
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved