Generated Files
一个thrift文件被编译后根据以下规则生成对应的文件:
- all constants go into a single .cpp/.h pair
- all type definitions (enums and structs) go into another .cpp/.h pair
- each service gets its own .cpp/.h pair
thrift的基本类型
bool
byte
、i16
、i32
、i64
:带符号的整形
double
:64位带符号的浮点类型
string
:UTF-8编码的文本
thrift中没有无符号的数据类型,因为并不是所有的编程语言都支持无符号数据类型。
复合类型
struct Person {
1: required string first_name,
2: optional string middle_name,
3: required string last_name,
4: i32 age = 0
}
符合类型中可以使用required
/optional(默认)
来修饰字段。
容器
thrift中的容器类型都是强类型的,因此声明时必须指定容器中元素的类型。
list
c++:STL vector;
java:ArrayList;
set
c++:STL set;
java:HashSet;
map
c++:STL map;
java:HashMap;
注释
apache thrift支持三种注释:#
、//
、/**/
document
apache thrift中,每一个.thrift
文件被称作一个document
。
头文件
thrift include
thrift文件:myfirst.thrift,文件内容:
#include "shared.thrift"
.....
在编译时,会在当前路径或者是指定的路径寻找头文件,编译时指定路径语法:
thrift --gen php -I ~/include myfirst.thrift
当在myfirst.thrift中需要访问shared.thrift文件中的对象时,使用文件名.对象名
的格式,例如:shared.thrift中存在struct mystruct
对象,在myfirst.thrift中使用shared.mystruct
的格式访问。
c++ include
如果想在编译.thrift后生成的文件中包含下面的头文件:
#include <vector>
则需要在.thrift文件中使用下面的格式:
cpp_include "<vector>"
namespace
不同的语言对于名字空间有不同的词汇,比如:名字空间,包,模块等,在thrift中统一称为uniformly namespaces
。 为特定语言指定名字空间:
namespace java myfirst
namespace php myfirstthrift
namespace py myfirstmodule
...
简便的方式是统一指定名字空间:
namespace * myfirst
即,所有语言的名字空间都叫做myfirst
。
方法
thrift中的方法可以使用oneway
修饰,代表的含义是:客户端只需要发起调用请求,而不需要等待该方法的返回结果,这类方法不会返回任何值,因此,方法的返回值为void
。