现在的位置: 首页 > 综合 > 正文

thrift介绍与学习

2018年04月02日 ⁄ 综合 ⁄ 共 2298字 ⁄ 字号 评论关闭

1.trhfit基本介绍

Thrift是 一个跨平台,支持多语言的,通过定义IDL文件,自动生成RPC客户端与服务端通信代码的工具集合,也可以说是框架。

与之相类似的还有google的protocolbuffer.

2.thrift官网

Thrift是由facebook开发,并于2008开源与Apache社区。

官网地址: http://thrift.apache.org/

源码下载地址: http://svn.apache.org/repos/asf/thrift/trunk

Wiki地址: http://wiki.apache.org/thrift/

Wiki上的资料我基本已经看完,上面的资料很棒,thrift学习最好的地方。

3.编译 jar包

Check thrift源码下来,在lib目录下有各个语言的源码。此文档以java为例

把java目录源码加入到eclipse工程中,会发现有build.xml文件,通过ant build,就会生成最新的thrift jar包。在linux环境下,需要在官网上下载最新的tar包源码,解压,然后通过ant也可编译出最新代码的jar包。在eclipse编译过程中,112行报出过异常,看错误提示为Notice与Lincene两个文件在拷贝时出错,后来通过手工拷贝,即完成了编译。

4.thrift基本类型

  基本类型有:

  bool:A boolean value (true or false)

byte: An 8-bit signed integer

i16: A 16-bit signed integer

i32: A 32-bit signed integer

i64: A 64-bit signed integer

double: A 64-bit floating point number

string: A text string encoded using UTF-8 encoding

Note the absence of unsigned integer types. This is due to the factthat there are no native unsigned integer types in many programming languages

  binary: a sequence of unencoded bytes (N.B.:This is currently a specialized form of the string type above,
added to providebetter interoperability with Java. The current plan-of-record is toelevate this to a base type at some point)

   此类型在IDL定义后,自动生成代码为java中的ByteBuffer类型,其client/server传替此属性,在get方法里得到是byte[]数组。此字段为java通讯中得到二进制流提供了很好的支持。

   容器有:list<type>   set<type>   map<type1,type2>(其类似于java中的ArrayList,HastSet,HashMap,详细的可以参考官网)

   Exception:是一个继承于本地语言的exception基类

   Service: The Thrift compiler generatesfully functional client and server stubs that implement the interface.

5.编译IDL文件。生成server/client接口定义的代码

  Thrift跟据定义的IDL接口,自动生成Server与Client定义的接口代码.此种方式因为是基于静态文件,每次修改接口,都需要双方重新生成代码。如果有基于动态要求的可能参考avro项目

  Thrift文件定义后,自动生成代码,可以在linux环境生成,也可以在window下生成(介绍在window下生成方法)在官网下载thrift-0.6.0.exe。

  定义IDL文件,user.thrift:

 namespace javacom.netease.thrift.test 

/**

 * 测试。

 * @param bstr  eml邮件的字节数组或者bytebuffer,约定为 字节数组就好了 此字段并*没在代码中用到

 */

struct User { 

 1:i32    userId, 

 2:string loginName, 

 3:string password, 

 4:string name,

 5:binary bstr

/**异常*/

exception UserNotFound { 

  1:string message 

}

service UserService { 

 User getUser(1:string loginName) throws (1:UserNotFound unf), 

 list<User> getUsers() 

}

thrift-0.6.0.exe与user.thrift都在e盘下的thrift目录下,DOS界面切换到thrift目录下,通过thrift –gen java user.thrift 回车

通过此命令,即自动生成我们想要的代码。包名为com.netease.thrift.test目录

 

6.编写server/client 示例程序。

 在附件中。提供下载。(下载地址:http://download.csdn.net/source/3495513)

Thrift相对而言,比较简单,通过官网的示例,可以很好的掌握它的使用。

另外Thrift 源码相对而言并不多,可以尝试看下它的源码实现。我努力中~

抱歉!评论已关闭.