這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
- thrift是什麼
- 依賴條件
- thrift安裝
- thrift使用
- 總結
thrift是什麼
Thrift是一種介面描述語言和二進位通訊協議,[1]它被用來定義和建立跨語言的服務。[2]它被當作一個遠端程序呼叫(RPC)架構來使用,是由Facebook為“大規模跨語言服務開發”而開發的。它通過一個代碼產生引擎聯合了一個軟體棧,來建立不同程度的、無縫的跨平台高效服務,可以使用C#、C++(基於POSIX相容系統)、Cappuccino、Cocoa、Delphi、Erlang、Go、Haskell、Java、Node.js、OCaml、Perl、PHP、Python、Ruby和Smalltalk。[wiki連結](https://zh.wikipedia.org/wiki/Thrift)
依賴條件
thrift核心代碼使用C++寫的,用了boost庫。執行以下命令,安裝相關依賴:
yum install automake libtool flex bison pkgconfig gcc-c++ boost-devel libevent-devel zlib-devel python-devel ruby-devel
thrift安裝
1.到http://thrift.apache.org/download 這裡下載的是 thrift-0.9.3.tar.gz
2. 在執行下列操作, 可根據需要選擇相應的語言支援
#tar -zxvf thrift-0.9.3.tar.gz #cd thrift-0.9.3#./configure --with-boost=/usr/local --without-java --without-php#make; make install
- 在終端輸入:thrift –version 查看是否安裝成功。
thrift使用
- 定義一個thrift檔案, phone.thrift, 內容如下:
enum PhoneType { HOME, WORK, MOBILE, OTHER}struct Phone { 1: i32 id, 2: string number, 3: PhoneType type}
- 使用thrift命令列,產生java, golang 代碼
thrift -r --gen cpp phone.thrift thrift -r --gen go phone.thrift
- 在gen-cpp目錄執行下列操作
cp PhoneService_server.skeleton.cpp PhoneService_server.cpp
- 修改 PhoneService_server.cpp 中的 get 函數
void get(Phone& _return, const std::string& uid) { // Your implementation goes here _return.id = 1024; _return.number = "13424562789"; _return.type = PhoneType::MOBILE; printf("get\n"); }
- 編寫makefile檔案
BOOST_PATH = /usr/include/boost/THRIFT_PATH = /usr/local/include/thriftLIB_PATH = /usr/local/libSRC = phone_types.cpp phone_constants.cpp PhoneService.cpp PhoneService_server.cppserver: ${SRC} g++ -g -o PhoneServer ${SRC} -I${THRIFT_PATH} -I{BOOST_PATH} -lthrift
運行make, 產生 PhoneServer 的可執行檔, 運行PhoneServer
./PhoneServer
- 準備golang的用戶端
#cd gen-go#mkdir src#mv phone src/phone#mv src/phone/phone_service-remote src/phone_service-remote
修改 /etc/profile檔案, 增加golang項目路徑
export GOPATH=/usr/local/gopath:/home/denny/thrift-test/gen-go
使環境變數生效
source /etc/profile
編譯 phone_service-remote
go build phone_service-remote
運行 phone_service-remote
./phone_service-remote
輸出:
Phone({ID:1024 Number:13424562789 Type:MOBILE}) <nil>
至此thrift的簡單應用就完結了
總結
對thrift研究也不是很多, 現在感覺來說thrift適合多語言混合編程,且系統內或系統間的互動依賴於RPC這時候的用處應該是挺大的。