子云小筑 ? Thrift简介

来源:百度文库 编辑:神马文学网 时间:2024/05/23 14:02:12

Thrift是一个跨语言服务部署框架,最初由Facebook于2007年开发,后于2008年进入Apache孵化器(Apache Incubator)。

类似于SOAP,COM和CORBA,Thrift通过定义一个中间定义语言和Thrift代码生成工具,生成指定语言的代码。目前,Thrift支持C++,Java,Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa,Smalltalk和OCaml的代码生成。

简单分析其机理,Thrift就是实现C/S模式,通过代码生成工具将接口定义文件生成服务器端和客户端代码(可以为不同语言),从而实现服务端和客户端跨语言的支持。

Thrift可以分为传输层和协议层:

1、传输层定义了数据的传输方式,可以为TCP/IP传输,内存共享或者文件共享等形式;
2、协议层定义了数据的传输格式,可以为二进制流或者XML等形式。

简单例子:

中间语言定义:

view sourceprint? 1 struct UserProfile { 2 1: i32 uid, 3 2: string name, 4 3: string blurb 5 } 6 service UserStorage { 7 void store(1: UserProfile user), 8 UserProfile retrieve(1: i32 uid) 9 }

Python客户端代码:

view sourceprint? 01 # Make an object 02 up = UserProfile(uid=1, 03                  name="Mark Slee", 04                  blurb="I'll find something to put here.") 05   06 # Talk to a server via TCP sockets, using a binary protocol 07 transport = TSocket.TSocket("localhost", 9090) 08 transport.open() 09 protocol = TBinaryProtocol.TBinaryProtocol(transport) 10   11 # Use the service we already defined 12 service = UserStorage.Client(protocol) 13 service.store(up) 14   15 # Retrieve something as well 16 up2 = service.retrieve(2)

服务器端代码:

view sourceprint? 01 class UserStorageHandler : virtual public UserStorageIf { 02  public: 03   UserStorageHandler() { 04     // Your initialization goes here 05   } 06   07   void store(const UserProfile& user) { 08     // Your implementation goes here 09     printf("store\n"); 10   } 11   12   void retrieve(UserProfile& _return, const int32_t uid) { 13     // Your implementation goes here 14     printf("retrieve\n"); 15   } 16 }; 17   18 int main(int argc, char **argv) { 19   int port = 9090; 20   shared_ptr handler(new UserStorageHandler()); 21   shared_ptr processor(new UserStorageProcessor(handler)); 22   shared_ptr serverTransport(new TServerSocket(port)); 23   shared_ptr transportFactory(new TBufferedTransportFactory()); 24   shared_ptr protocolFactory(new TBinaryProtocolFactory()); 25   TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); 26   server.serve(); 27   return 0; 28 }

参考资料

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