Thrift 用法简介
本章简要介绍了 Thrift 的数据结构和语法,给出了如何定义服务的示例
Base Types
• bool: A boolean value (true or false), one byte
• byte: A signed byte
• 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: Encoding agnostic text or binary string
*Note that the thrift does not support unsigned intergers.*
Containers
• list<t1>: An ordered list of elements of type t1. May contain duplicates.
• set<t1>: An unordered set of unique elements of type t1.
• map<t1,t2>: A map of strictly unique keys of type t1 to values of type t2.
*Types used in containers many be any valid Thrift type (including structs and exceptions) excluding services.*
Structs and Exceptions
Structs 在面向对象的语言中被翻译成类
语法上 Exception 与 Struct 相同,在语义上不同
Services
等价于在面向对象的语言中定义一个接口 interface (或一个纯虚类 pure virtual abstract class)
Type define
typedef i32 MyInteger
typedef Tweet ReTweet
注意:
- 末尾没有分号
- 结构体也能够使用 typedef
Enums
enum TweetType {
TWEET, // 1
RETWEET = 2, // 2
DM = 0xa, // 3
REPLY
}
struct Tweet {
1: required i32 userId;
2: required string userName;
3: required string text;
4: optional Location loc;
5: optional TweetType tweetType = TweetType.TWEET // 5
16: optional string language = "english"
}
注意:
ENUM 类似 C 语言风格,编译器默认从 0 开始分配值
也可以自己定义
允许 16 进制
Comments
与 C 语言相同
/ *
*注释内容
** /
// 注释内容
Namespaces
Thrift 自动根据语言转换
namespace cpp com.example.project (1)
namespace java com.example.project (2)
(1) Translates to namespace com { namespace example { namespace project {
(2) Translates to package com.example.project
Includes
能够包含其他文件
include "tweet.thrift" // 1
...
struct TweetSearchResult {
1: list<tweet.Tweet> tweets; // 2
}
Constants
const i32 INT_CONST = 1234; // 1
const map<string,string> MAP_CONST = {"hello": "world", "goodnight": "moon"}
Defining Structs
struct Location { // 1
1: required double latitude;
2: required double longitude;
}
struct Tweet {
1: required i32 userId; // 2
2: required string userName; // 3
3: required string text;
4: optional Location loc; // 4
16: optional string language = "english" // 5
}
注意:
每一个字段前面 必须 有一个唯一的正 ID
字段可能被标记为 required 或者 optional
Defining Services
service Twitter {
void ping(), // 1
bool postTweet(1:Tweet tweet); // 2
TweetSearchResult searchTweets(1:string query); // 3
oneway void zip() // 4
}