一、简介
thrfit是跨语言的rpc框架,这里介绍thrift文件的定义(各种数据类型)和生成接口方式。
二、thrift数据类型和结构
thrift数据类型和结构,官网地址:http://thrift.apache.org/docs/types
1、基本类型
这里直接引用官网上的定义,很好理解
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
2、字节类型
binary: a sequence of unencoded bytes
3、集合类型
list: 列表,定义时可直接赋值,如: list<string> stuNameList=["apple", "pearl"]
set: 集合
map: 映射
4、enum枚举类型
enum定义枚举类型,默认从0开始赋值,也可以指定常量值 ,如:
enum level{ GradeOne, GradeTwo=2, GradeThree=3 }
5、struct结构体
struct结构体定义实体(如java中的class),
字段格式为:序号: 类型 名称
示例如:
struct Stu{ 1: required string stuNo, 2: optional i32 stuAge, 3: bool isPass }
6、service接口
service定义接口(接口可exetend其它接口),包含方法,参数同struct一样,需要加序号,如:
service Hello{ Stu buildStu(1:string stuName); }
7、const常量
const定义常量,如:const i32 step=3;
8、namespace包名
namespace定义包名,放在文件头,结构为:namespace 语言 包名
如:
namespace java com.dragon.study.thrift
三、thrift文件完整示例
thrift文件完整示例,如:
namespace java com.dragon.study.thrift //namespace py ThriftTest //添加其它文件 //include "type.thrift" const i32 step=3; const map<string,i32> stuNameAgeMap={"apple":11, "pearl":18} const list<string> stuNameList=["apple", "pearl"] const set<string> schoolNameSet=["sun", "moon"] struct Stu{ 1: required string stuNo, 2: optional i32 stuAge, 3: bool isPass } enum level{ GradeOne=1, GradeTwo=2, GradeThree=3 } service Hello{ Stu buildStu(1:string stuName); }
四、thrift文件生成具体语言接口
thrift文件定义完后,接下来就需要根据文件生成指定语言文件的接口。
1、工具thrift.exe生成
下载生成工具 http://mirror.bit.edu.cn/apache/thrift/0.10.0/thrift-0.10.0.exe
执行命令:thrift --gen <language> <Thrift filename>
如:thrift.exe -gen java ThriftStudy.thrift
空类型
void