Apache Thrift的簡單使用

來源:互聯網
上載者:User

標籤:style   http   io   os   使用   ar   java   for   檔案   

 

Apache Thrift的簡單使用

----------------------

 

1. 簡介

Thrift是Facebook的一個開源項目,主要是一個跨語言的服務開發架構。它有一個代碼產生器來對它所定義的IDL定義檔案自己主動產生服務代碼架構。使用者僅僅要在其之前進行二次開發即可,對於底層的RPC通訊等都是透明的。眼下它支援的語言有C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, and OCaml.

 

2. 下載與安裝

能夠在http://incubator.apache.org/thrift/download/去下載它的最新版本號碼,眼下最新版本號碼是0.5.0。另外你也能夠check出它的svn,方法例如以下:

svn co http://svn.apache.org/repos/asf/thrift/trunk thrift

cd thrift

 

在它的jira中看到,它的0.6版本號碼也非常快就會出來了。

 

我的本本是debian 6.0,假設用ubuntu的兄弟安裝方法也是一樣的

tar -zxvf thrift-0.5.0.tar.gzcd thrift-0.5.0./configuremake sudo make install 

 

這時thrift的代碼產生器和一些庫檔案就產生好了。

 

你能夠用例如以下命令看一下thrift的版本號碼資訊

 

thrift -version 

 

3. 一個簡單的範例

在thrift源碼檔案夾有一個叫tutorial的檔案夾,進行當中後執行thrift命令產生對應的服務代碼:

$ thrift -r --gen cpp tutorial.thrift // -r對當中include的檔案也產生服務代碼 -gen是產生服務代碼的語言 

 

執行完之後會在當前檔案夾看到一個gen-cpp檔案夾,當中就是thrfit命令產生的程式碼

 

這時你cd到tutorial/cpp檔案夾,執行make,產生對應的CppServer與CppClient程式。

 

這時你能夠用./CppServer執行服務端,讓其監聽一個特定的port

 

這時你能夠用./CppClient執行client程式,讓其去串連服務端,調用其所相應的服務。預設調用後會輸出例如以下資訊:

 

lemo@debian:~/Workspace/Facebook/Thrift/thrift-0.5.0/tutorial/cpp$ ./CppServerStarting the server...ping()add(1,1)calculate(1,{4,1,0})calculate(1,{2,15,10})getStruct(1) 

 

假設你的終端中也出現了如上的資訊,恭喜你,執行成功了。假設在執行CppServer的時候找不到動態庫,看看你是不是執行了make install,假設執行了,再執行一下sudo ldconfig試試。再用ldd CppServer看一下它有沒有找到對應的動態庫了。

 

4. 範例分析

 

4.1 Thrift IDL的分析

 

這邊有兩個IDL檔案,內容例如以下:

 

shared.thrift---------------** * This Thrift file can be included by other Thrift files that want to share * these definitions. */namespace cpp sharednamespace java sharednamespace perl shared// 這裡定義了一個結構體,未定義方法,相應於產生的程式碼在gen-cpp中的shared_types.h中,當中有一個class叫SharedStruct,// 有沒有看到當中有兩個方法叫read和write,這就是用來對其進行序列化與把序列化的方法.// 對了,當中的i32是Thrift IDL中定義的變數類型,相應於c++語言中的int32_tstruct SharedStruct { 1: i32 key 2: string value}// 這裡定義的一個服務,它語義上相似於物件導向中的定義一個介面,thrift的編譯器會對其產生一套實現其介面的client與服務端方法// 服務的一般定義格式例如以下// service <name>// <returntype> <name>(<arguments>)// [ throws (<exceptions>)]// ...// }service SharedService { SharedStruct getStruct(1: i32 key)}tutorial.thrift----------------/** * Thrift files can reference other Thrift files to include common struct * and service definitions. These are found using the current path, or by * searching relative to any paths specified with the -I compiler flag. * * Included objects are accessed using the name of the .thrift file as a * prefix. i.e. shared.SharedObject */ // 這個IDL包括了還有一個IDL,也就是說還有一個IDL中的對象與服務對其時可見的include "shared.thrift"/** * Thrift files can namespace, package, or prefix their output in various * target languages. */ // 這裡定義了一些語言的namespace空間namespace cpp tutorialnamespace java tutorialnamespace php tutorialnamespace perl tutorial/** * Thrift lets you do typedefs to get pretty names for your types. Standard * C style here. */ // 自己定義類型typedef i32 MyInteger/** * Thrift also lets you define constants for use across languages. Complex * types and structs are specified using JSON notation. */ // 定義一些變數const i32 INT32CONSTANT = 9853const map<string,string> MAPCONSTANT = {‘hello‘:‘world‘, ‘goodnight‘:‘moon‘}/** * You can define enums, which are just 32 bit integers. Values are optional * and start at 1 if not supplied, C style again. */ // 定義枚舉類型enum Operation { ADD = 1, SUBTRACT = 2, MULTIPLY = 3, DIVIDE = 4}/** * Structs are the basic complex data structures. They are comprised of fields * which each have an integer identifier, a type, a symbolic name, and an * optional default value. * * Fields can be declared "optional", which ensures they will not be included * in the serialized output if they aren‘t set. Note that this requires some * manual management in some languages. */struct Work { 1: i32 num1 = 0, 2: i32 num2, 3: Operation op, 4: optional string comment, //這裡的optional欄位類型表示假設這個欄位的值沒有被賦值,它就不會被序列化輸出}/** * Structs can also be exceptions, if they are nasty. */ // 這裡定義了一些異常exception InvalidOperation { 1: i32 what, 2: string why}/** * Ahh, now onto the cool part, defining a service. Services just need a name * and can optionally inherit from another service using the extends keyword. */ // 這裡是定義服務,它繼承了shared的服務service Calculator extends shared.SharedService { /** * A method definition looks like C code. It has a return type, arguments, * and optionally a list of exceptions that it may throw. Note that argument * lists and exception lists are specified using the exact same syntax as * field lists in struct or exception definitions. */ void ping(), i32 add(1:i32 num1, 2:i32 num2), i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch), /** * This method has a oneway modifier. That means the client only makes * a request and does not listen for any response at all. Oneway methods * must be void. */ oneway void zip()} 

 

4.2 服務端與client代碼的分析   4.2.1 c++服務端

   在tutorial/cpp檔案夾中的CppServer.cpp是它的服務代碼,主要分成兩部分,

   一部分是main方法用於做一些初始化與服務的啟動,第二部分對於IDL中定義的介面的實現

  int main(int argc, char **argv) {// 定義了RPC的協議工廠,這裡使用了二進位協議,你不能夠使用別的協議,如JSON,Compact等shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());// 這裡產生使用者實現的CalculatorHandler服務,再把其幫定到一個Processor上去,它主要用於處理協議的輸入與輸出資料流shared_ptr<CalculatorHandler> handler(new CalculatorHandler());shared_ptr<TProcessor> processor(new CalculatorProcessor(handler));// 產生一個傳輸通道,這裡使用了Socket方式shared_ptr<TServerTransport> serverTransport(new TServerSocket(9090));// 產生一個傳輸工廠,主要用於把上面的transport轉換成一個新的應用程式層傳輸通道shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());// 產生一個簡單的服務端,這是一個單線程的服務端 TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);// 你也能夠產生一個多線程的服務端,就是對其添?線程池。但它如今還不支援進程池,但可能會在0.7版本號碼中進行支援。 /** * Or you could do one of these shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workerCount); shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory>(new PosixThreadFactory()); threadManager->threadFactory(threadFactory); threadManager->start(); TThreadPoolServer server(processor, serverTransport, transportFactory, protocolFactory, threadManager); TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory); */ printf("Starting the server.../n"); server.serve(); // 啟動服務 printf("done./n"); return 0;} 

 

 

還有一部分例如以下:

// 這一部分主要是實現介面類,用於提供給對應的服務使用。class CalculatorHandler : public CalculatorIf {public: CalculatorHandler() {} void ping() { printf("ping()/n"); } int32_t add(const int32_t n1, const int32_t n2) { ... } int32_t calculate(const int32_t logid, const Work &work) { ... } void getStruct(SharedStruct &ret, const int32_t logid) { ... } void zip() { printf("zip()/n"); }protected: map<int32_t, SharedStruct> log;}; 

4.2.2 c++client

int main(int argc, char** argv) { // 產生一個Socket串連到服務端 shared_ptr<TTransport> socket(new TSocket("localhost", 9090)); // 對Socket通道添?緩衝功能 shared_ptr<TTransport> transport(new TBufferedTransport(socket)); // 產生對應的二進位協議,這個要和服務端一致,不然會出現協議版本號碼不正確的錯誤 shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); // 產生client的服務物件 CalculatorClient client(protocol); try { transport->open(); // 加開服務 // 調用事先定義好的服務介面 client.ping(); printf("ping()/n"); int32_t sum = client.add(1,1); printf("1+1=%d/n", sum); Work work; work.op = Operation::DIVIDE; work.num1 = 1; work.num2 = 0; try { int32_t quotient = client.calculate(1, work); printf("Whoa? We can divide by zero!/n"); } catch (InvalidOperation &io) { printf("InvalidOperation: %s/n", io.why.c_str()); } work.op = Operation::SUBTRACT; work.num1 = 15; work.num2 = 10; int32_t diff = client.calculate(1, work); printf("15-10=%d/n", diff); // Note that C++ uses return by reference for complex types to avoid // costly copy construction SharedStruct ss; client.getStruct(ss, 1); printf("Check log: %s/n", ss.value.c_str()); // 關閉服務 transport->close(); } catch (TException &tx) { printf("ERROR: %s/n", tx.what()); }} 

4.2.3 其他代碼的實現

在tutorial檔案夾中有其他代碼的範例,如erl,java,python,perl,ruby等。

 

5 參考

1. http://incubator.apache.org/thrift/

2. http://incubator.apache.org/thrift/static/thrift-20070401.pdf

 

Apache Thrift的簡單使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.