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
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值