打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
子云小筑 ? Thrift简介

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等形式。

简单例子:

中间语言定义:

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客户端代码:

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)

服务器端代码:

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<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);
26   server.serve();
27   return 0;
28 }

参考资料

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用Thrift RPC编写程序
使用thrift作为go和C++中间rpc及问题(一) | Go语言中文网 | Golang中文社区 | Golang中国
thrift笔记
Thrift使用指南 | 董的博客
C++多线程编程总结
Android系统的Binder机制
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服