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等形式。
简单例子:
中间语言定义:
7 |
void store(1: UserProfile user), |
8 |
UserProfile retrieve(1: i32 uid) |
Python客户端代码:
02 |
up = UserProfile(uid = 1 , |
04 |
blurb = "I'll find something to put here." ) |
06 |
# Talk to a server via TCP sockets, using a binary protocol |
07 |
transport = TSocket.TSocket( "localhost" , 9090 ) |
09 |
protocol = TBinaryProtocol.TBinaryProtocol(transport) |
11 |
# Use the service we already defined |
12 |
service = UserStorage.Client(protocol) |
15 |
# Retrieve something as well |
16 |
up2 = service.retrieve( 2 ) |
服务器端代码:
01 |
class UserStorageHandler : virtual public UserStorageIf { |
03 |
UserStorageHandler() { |
04 |
// Your initialization goes here |
07 |
void store( const UserProfile& user) { |
08 |
// Your implementation goes here |
12 |
void retrieve(UserProfile& _return, const int32_t uid) { |
13 |
// Your implementation goes here |
18 |
int main( int argc, char **argv) { |
20 |
shared_ptr<UserStorageHandler> handler( new UserStorageHandler()); |
21 |
shared_ptr<TProcessor> processor( new UserStorageProcessor(handler)); |
22 |
shared_ptr<TServerTransport> serverTransport( new TServerSocket(port)); |
23 |
shared_ptr<TTransportFactory> transportFactory( new TBufferedTransportFactory()); |
24 |
shared_ptr<TProtocolFactory> protocolFactory( new TBinaryProtocolFactory()); |
25 |
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); |
参考资料
1. http://incubator.apache.org/thrift
本文来自 http://www.imneio.com/2009/10/thrift-intro/
转载请保留原作者链接,谢谢!!!