thrift文件詳解

本文介紹如何在一個.thrift文件中使用thrift. 

首先要注意的是, .thrift文件支持標準shell註釋,這使得thrift文件可執行,並可以在頂部行include thrift,可以在任意位置進行註釋。


test.thrift:

/**
 * 首先是數據類型,thrift支持的數據類型爲:
 *
 *  bool        Boolean, one byte
 *  i8 (byte)   Signed 8-bit integer
 *  i16         Signed 16-bit integer
 *  i32         Signed 32-bit integer
 *  i64         Signed 64-bit integer
 *  double      64-bit floating point value
 *  string      String
 *  binary      Blob (字節數組)
 *  map<t1,t2>  Map from one type to another
 *  list<t1>    一種類型的有序list
 *  set<t1>     Set of unique elements of one type
 *
 * thrift支持C類型的註釋
 */

// thrift也支持像C一樣的單行註釋

/**
 * thrift文件可以引用其他thrift文件以包含常見的結構和服務定義
 * 可以使用當前路徑找到,或通過搜索-l編譯器標誌指定的任何路徑進行搜索
 *
 * 使用.thrift文件的名稱作爲前綴訪問包含的對象,例如shared.SharedObject
 */
include "shared.thrift"

/**
 * Thrift文件可以以各種目標語言對其輸出進行namespace、package或prefix
 */
namespace cpp tutorial
namespace d tutorial
namespace dart tutorial
namespace java tutorial
namespace php tutorial
namespace perl tutorial
namespace haxe tutorial
namespace netcore tutorial

/**
 * Thrift 可以做typedef來給你的類型起別名,這也是標準的C風格
 */
typedef i32 MyInteger

/**
 * Thrift 還允許你定義用於跨語言的常量. 
 * 複雜的類型和結構體可以通過json表示法進行指定.
 */
const i32 INT32CONSTANT = 9853
const map<string,string> MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}

/**
 * 還可以定義enum類型,也就是32bit的整形. 
 * 值是可選項,如果沒有定義,默認從1開始,C風格
 */
enum Operation {
  ADD = 1,
  SUBTRACT = 2,
  MULTIPLY = 3,
  DIVIDE = 4
}

/**
 * 結構體是基本的複雜數據結構. 
 * 它們由每個具有整數標識符,類型,符號名稱和可選缺省值的字段組成
 *
 * 字段可以被聲明爲"optional", 這確保瞭如果它們未被設置的話,
 * 會不被包括在序列化輸出中。
 */
struct Work {
  1: i32 num1 = 0,
  2: i32 num2,
  3: Operation op,
  4: optional string comment,
}

/**
 * 結構也可以是例外,如果它們很討厭。
 */
exception InvalidOperation {
  1: i32 whatOp,
  2: string why
}

/**
 * 重要性能,定義一個service. 
 * service只需要一個名稱,並可以選擇使用extend關鍵字從另一個服務繼承
 */
service Calculator extends shared.SharedService {

  /**
   * method定義看起來像C代碼. 有返回類型、參數以及可能會拋出的異常列表
   * 參數列表和異常列表使用與結構體或異常定義中的字段列表完全相同的語法來定義
   */

   void ping(),

   i32 add(1:i32 num1, 2:i32 num2),

   i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),

   /**
    * 此method具有單向修飾符. 這意味着客戶端只提出請求,並且根本不listen任何響應
    * 單向method必須void
    */
   oneway void zip()

}


shared.thrift

/**
 * 該thrift文件可以包含在想共享這些定義的其他thrift文件中
 */

namespace cpp shared
namespace d share // "shared" would collide with the eponymous D keyword.
namespace dart shared
namespace java shared
namespace perl shared
namespace php shared
namespace haxe shared
namespace netcore shared

struct SharedStruct {
  1: i32 key
  2: string value
}

service SharedService {
  SharedStruct getStruct(1: i32 key)
}


參考:

http://thrift.apache.org/




發佈了84 篇原創文章 · 獲贊 148 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章