前言:
Thrift作為Facebook開源的RPC框架, 通過IDL中間語言, 並借助代碼生成引擎生成各種主流語言的rpc框架服務端/客戶端代碼. 不過Thrift的實現, 簡單使用離實際生產環境還是有一定距離, 本系列將對Thrift作代碼解讀和框架擴充, 使得它更加貼近生產環境. 本文主要講解Thrift的初體驗, 使得開發者對thrift有個初步的認識.
Thrift 軟件棧
Thrift對軟件棧的定義非常的清晰, 使得各個組件能夠松散的耦合, 針對不同的應用場景, 選擇不同是方式去搭建服務.

評注:
Transport: 傳輸層,定義數據傳輸方式,可以為TCP/IP傳輸,內存共享或者文件共享等
protocol: 協議層, 定義數據傳輸格式,可以為二進制或者XML等
Processor: 處理層, 這部分由定義的idl來生成, 封裝了協議輸入輸出流, 並委托給用戶實現的handler進行處理.
Server: 服務層, 整合上述組件, 提供網絡模型(單線程/多線程/事件驅動), 最終形成真正的服務.
Thrift 對語言的支持
Thrift和Google Protobuf相比, 都提供了可擴展序列化機制, 不但兼容性好而且壓縮率高. 兩者在這塊各有長短, 性能上PB稍有優勢. 但在語言的支持度上, Protobuf只支持c++/java/python這三種主流的語言, Thrift則幾乎覆蓋了大部分的語言, 從這點上來說, Thrift的優勢非常的明顯.
Thrift 支持的數據類型
基本類型:
bool: 布爾值
byte: 8位有符號整數
i16: 16位有符號整數
i32: 32位有符號整數
i64: 64位有符號整數
double: 64位浮點數
string: UTF-8編碼的字符串
binary: 二進制串
結構體類型:
struct: 定義的結構體對象
容器類型:
list: 有序元素列表
set: 無序無重復元素集合
map: 有序的key/value集合
異常類型:
exception: 異常類型
服務類型:
service: 具體對應服務的類
小試牛刀
1) 定義IDL文件
#). 編輯hello.thrift
namespace java com.mmxf.service.demo
service HelloService {
string hello(1: string name);
}
#) thrift -gen java hello.thrift
生成的代碼目錄結構如下: 
2). 服務端代碼
public class ServerDemo {
// *) 定義實現服務類
public static class HelloServiceImpl implements HelloService.Iface {
@Override
public String hello(String name) throws TException {
return "hello " + name;
}
}
public static void main(String[] args) throws TTransportException {
// *) 傳輸層(Transport), 設置監聽端口為9000
TServerSocket serverTransport = new TServerSocket(9000);
// *) 協議層
Factory protocolFactory = new TBinaryProtocol.Factory(true, true);
// *) 處理層(Processor)
HelloServiceImpl handler = new HelloServiceImpl();
HelloService.Processor<HelloServiceImpl> processor =
new HelloService.Processor<HelloServiceImpl>(handler);
// *) 服務層(Server)
TServer server = new TThreadPoolServer(
new TThreadPoolServer.Args(serverTransport)
.protocolFactory(protocolFactory)
.processor(processor)
);
// *) 啟動監聽服務
server.serve();
}
}
3). 客戶端代碼
public class ClientDemo {
public static void main(String[] args) throws TException {
// *) 傳輸層
TTransport transport = new TSocket("localhost", 9000);
transport.open();
// *) 協議層, 與服務端對應
TProtocol protocol = new TBinaryProtocol(transport);
// *) 創建RPC客戶端
HelloService.Client client = new HelloService.Client(protocol);
// *) 調用服務
System.out.println(client.hello("lilei"));
// *) 關閉句柄
transport.close();
}
}
4). 結果驗證
hello lilei
5). 配置maven依賴, 使用thrift 0.9.0版本
<dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.0</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency>
后續
后續講解服務端的各種網絡模型, 以及讀寫超時控制, 敬請期待.
