thrift


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

install

use the yifeikong/dotfiles/install/install_thrfit.sh to install

types

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

no support for unsigned types

struct

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

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

containers

list set map

exceptions

exceptions are just another name for struct

services

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)
}

namespace

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

namespace py tutorial
namespace java tutorial

include

include "other.thrift"

generate

thrift -r --gen py file.thrift

-r means recursively, --gen gives language

YN: 线程安全性

1. thrift默认提供了thread/process 等不同的server类型, 需要考虑handler的线程安全问题
2. thrift client不是线程安全的, 在多线程程序中使用需要注意(http://grokbase.com/t/thrift/user/127yhv7wmx/is-the-thrift-client-thread-safe)
3. 看一下pyutil中是如何使用的...

eleme的thriftpy只支持多线程

handler 对应实现 service Server 中使用 Handler https://thrift-tutorial.readthedocs.io/en/latest/usage-example.html#a-simple-example-to-warm-up

重要的概念,包括 protocol 和 transport

http://thrift-tutorial.readthedocs.io/en/latest/index.html

https://diwakergupta.github.io/thrift-missing-guide/

Python的 server 和 client http://thrift.apache.org/tutorial/py

FAQ

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

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

如果只是同一个语言内,需要读写一些数据库之类的,封装成一个类就可以了

Const应该定义在哪儿?

如果是一个需要在调用过程中使用的常量,使用 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.

https://stackoverflow.com/questions/9732381/why-thrift-why-not-http-rpcjsongzip


评论区