1. 程式人生 > >Thrift 用法簡介

Thrift 用法簡介

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

注意:

  1. 末尾沒有分號
  2. 結構體也能夠使用 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
}