Thrift基本使用

来源:互联网 发布:qq游戏大厅 mac 编辑:程序博客网 时间:2024/04/29 01:50

thrift属于facebook.com技术核心框架之一,使用不同开发语言开发的系统可以通过该框架实现彼此间的通讯,开发者只需编辑一份thrift脚本,即可自动获得其它开发语言的代码(比如 c++ java python ruby c# haskell ocmal erlang cocoa php squeak).
thrift侧重点是构建夸语言的可伸缩的服务,特点就是支持的语言多,同时提供了完整的rpc service framework,可以很方便的直接构建服务,不需要做太多其他的工作。服务端可以根据需要编译成simple | thread-pool | threaded | nonblocking等方式;
thrift支持多种协议格,Thrift的代码实现,有专门的TProtocol和TTransport抽象,相互配合,可以实现多种协议,方便集成各种传输方式,目前支持xml、json等。
使用了epool
Apache软件基金会已将Thrift作为孵化器项目纳入其中。
thrift目前不支持Windows平台,不过有牛人已经在cygwin上编译调试通过了。
官方开发白皮书:http://incubator.apache.org/thrift/static/thrift-20070401.pdf

1 根据需求,书写 .thrift 服务接口文件 [用tutorial里的demo]
1.1 需要事先了解 ThriftTypes,对应各语言的本地类型
http://wiki.apache.org/thrift/ThriftTypes
1.2 了解thrift 接口定义语言 Thrfit IDL来写 .thrift文件
http://wiki.apache.org/thrift/ThriftIDL
1.3 .thrift 接口文件

/**

* This Thrift file can be included by other Thrift files that want to share

* these definitions.

*/

 

namespace cpp shared

namespace java shared

namespace perl shared

 

struct SharedStruct {

1: i32 key

2: string value

}//定义一个结构体

//定义一个服务

service SharedService {

SharedStruct getStruct(1: i32 key)

}

thrift的类型有如下几种:

/**

* The first thing to know about are types. The available types in Thrift are:

*

* bool        Boolean, one byte

* byte        Signed byte

* i16         Signed 16-bit integer

* i32         Signed 32-bit integer

* i64         Signed 64-bit integer

* double      64-bit floating point value

* string      String

* binary      Blob (byte array)

* map<t1,t2> Map from one type to another

* list<t1>    Ordered list of one type

* set<t1>     Set of unique elements of one type

*

* Did you also notice that Thrift supports C style comments?

*/

其中 list<t1>    Ordered list of one type对应C++中的vector<t1>

使用下面的语句,生成cpp骨架文件

thrift –r –gen cpp service.thrift

生成7个文件,分别是由service.thrift脚本定义的类型文件四个,两个.h文件(service_constants.h,service_types.h),两个对应的.cpp文件(service_constants.cpp,service_types.cpp)。service_types对应的文件中,定义了对应的由service.thrift脚本定义的类型。例如struct SharedStruct对应到一个类。另外三个文件分别是由service.thrift脚本中所定义的服务相关的文件,分别是SharedService .h,SharedService .cpp,以及SharedService_server.skeleton.cpp 骨架文件,我们只需要修改SharedService_server.skeleton.cpp 骨架文件中相关的接口部分的逻辑,即可生成对应的服务。