Author: yifei / Created: June 23, 2017, 11:45 p.m. / Modified: June 24, 2017, midnight / Edit


use the yifeikong/dotfiles/install/ to install


bool, byte(8-bit), i16, i32, i64, double, string

no support for unsigned types


struct is composition type, note, you have to add order prefix

struct Cat {
    1: required i32 number=10;
    2: optional i64 bigNumber;
    3:double decimal;
    4:string name="thrifty"


enum Operation {
    ADD = 1;
        SUB = 2;
        MUL = 3;
        DIV = 4;


list set map


exceptions are just another name for struct


service is interface.

NOTE the oneway modifier, which meas the client does not wait for response.

service StringCache {
    void set(1:i32 key, 2:string value),
        string get(1:i32 key) throws (1:KeyNotFound knf),
        oneway void delete(1:i32 key)


for each thrift file, you have to add a namespace for it.

namespace py tutorial
namespace java tutorial


include "other.thrift"


thrift -r --gen py file.thrift

-r means recursively, --gen gives language

YN: 线程安全性

1. thrift默认提供了thread/process 等不同的server类型, 需要考虑handler的线程安全问题
2. thrift client不是线程安全的, 在多线程程序中使用需要注意(
3. 看一下pyutil中是如何使用的...


handler 对应实现 service Server 中使用 Handler

重要的概念,包括 protocol 和 transport

Python的 server 和 client


何时需要一个 thrift 服务呢?而不是封装一个类或者 dal 来操作?

  1. 跨语言,跨代码库的调用
  2. 需要维持一个很重的资源的服务



如果是一个需要在调用过程中使用的常量,使用 thrift,如果是在数据库中存储,使用在代码中定义的常量Thrift vs http api

Thrift vs http api

A few reasons other than speed:

  1. Thrift generates the client and server code completely, including the data structures you are passing, so you don't have to deal with anything other than writing the handlers and invoking the client. and everything, including parameters and returns are automatically validated and parsed. so you are getting sanity checks on your data for free.
  2. Thrift is more compact than HTTP, and can easily be extended to support things like encryption, compression, non blocking IO, etc.
  3. Thrift can be set up to use HTTP and JSON pretty easily if you want it (say if your client is somewhere on the internet and needs to pass firewalls)
  4. Thrift supports persistent connections and avoids the continuous TCP and HTTP handshakes that HTTP incurs.

Personally, I use thrift for internal LAN RPC and HTTP when I need connections from outside.