1.trhfit基本介紹
Thrift是 一個跨平臺,支持多語言的,通過定義IDL文件,自動生成RPC客戶端與服務端通信代碼的工具集合,也可以說是框架。
與之相類似的還有google的protocolbuffer.
2.thrift官網
Thrift是由facebook開發,並於2008開源與Apache社區。
官網地址: http://thrift.apache.org/
源碼下載地址: http://svn.apache.org/repos/asf/thrift/trunk
Wiki地址: http://wiki.apache.org/thrift/
Wiki上的資料我基本已經看完,上面的資料很棒,thrift學習最好的地方。
3.編譯 jar包
Check thrift源碼下來,在lib目錄下有各個語言的源碼。此文檔以java爲例
把java目錄源碼加入到eclipse工程中,會發現有build.xml文件,通過ant build,就會生成最新的thrift jar包。在linux環境下,需要在官網上下載最新的tar包源碼,解壓,然後通過ant也可編譯出最新代碼的jar包。在eclipse編譯過程中,112行報出過異常,看錯誤提示爲Notice與Lincene兩個文件在拷貝時出錯,後來通過手工拷貝,即完成了編譯。
4.thrift基本類型。
基本類型有:
bool:A boolean value (true or false)
byte: An 8-bit signed integer
i16: A 16-bit signed integer
i32: A 32-bit signed integer
i64: A 64-bit signed integer
double: A 64-bit floating point number
string: A text string encoded using UTF-8 encoding
Note the absence of unsigned integer types. This is due to the factthat there are no native unsigned integer types in many programming languages
binary: a sequence of unencoded bytes (N.B.:This is currently a specialized form of the string type above, added to providebetter interoperability with Java. The current plan-of-record is toelevate this to a base type at some point)
此類型在IDL定義後,自動生成代碼爲java中的ByteBuffer類型,其client/server傳替此屬性,在get方法裏得到是byte[]數組。此字段爲java通訊中得到二進制流提供了很好的支持。
容器有:list<type> set<type> map<type1,type2>(其類似於java中的ArrayList,HastSet,HashMap,詳細的可以參考官網)
Exception:是一個繼承於本地語言的exception基類
Service: The Thrift compiler generatesfully functional client and server stubs that implement the interface.
5.編譯IDL文件。生成server/client接口定義的代碼。
Thrift跟據定義的IDL接口,自動生成Server與Client定義的接口代碼.此種方式因爲是基於靜態文件,每次修改接口,都需要雙方重新生成代碼。如果有基於動態要求的可能參考avro項目。
Thrift文件定義後,自動生成代碼,可以在linux環境生成,也可以在window下生成(介紹在window下生成方法)在官網下載thrift-0.6.0.exe。
定義IDL文件,user.thrift:
namespace javacom.netease.thrift.test
/**
* 測試。
* @param bstr eml郵件的字節數組或者bytebuffer,約定爲 字節數組就好了 此字段並*沒在代碼中用到
*/
struct User {
1:i32 userId,
2:string loginName,
3:string password,
4:string name,
5:binary bstr
}
/**異常*/
exception UserNotFound {
1:string message
}
service UserService {
User getUser(1:string loginName) throws (1:UserNotFound unf),
list<User> getUsers()
}
thrift-0.6.0.exe與user.thrift都在e盤下的thrift目錄下,DOS界面切換到thrift目錄下,通過thrift –gen java user.thrift 回車
通過此命令,即自動生成我們想要的代碼。包名爲com.netease.thrift.test目錄
6.編寫server/client 示例程序。
在附件中。提供下載。(下載地址:http://download.csdn.net/source/3495513)
Thrift相對而言,比較簡單,通過官網的示例,可以很好的掌握它的使用。
另外Thrift 源碼相對而言並不多,可以嘗試看下它的源碼實現。我努力中~