Thrift序列化和反序列化(JAVA版)

Thrift支持的类型

  • bool: 布尔型 A boolean value (true or false)
  • byte: 字节 An 8-bit signed integer
  • i16: 16位有符号整数 A 16-bit signed integer
  • i32: 32位有符号整数 A 32-bit signed integer
  • i64: 64位有符号整数 A 64-bit signed integer
  • double: 64为浮点数 A 64-bit floating point number
  • string: UTF-8字符串 A text string encoded using UTF-8 encoding
  • binary: a sequence of unencoded bytes

典型的IDL定义文件是这样的

#thrift
#demo.thrift
namespace java com.test.dto

struct DemoMessage {
    1: string home,
    2: i32 age,
    3: string name,
    4: optional i32 high,
    5: optional i64 time,

}

通过thrift命令可以生成Java定义文件 thrift --gen java demo.thrift

序列化

try {

    TMemoryBuffer mb = new TMemoryBuffer(64);
    TBinaryProtocol proto = new TBinaryProtocol(mb);
    DemoMessage data = new DemoMessage();
    data.setHome("my home address");
    data.setName("sam");
    data.setAge(20);
    //...
    data.write(proto);

    byte[] bytes = mb.getArray();
} catch (TException e) {
    e.printStackTrace();
}

反序列化

try {
    //byte[] bytes = mb.getArray();

    TMemoryBuffer mb = new TMemoryBuffer(64);
    mb.write(bytes);
    TBinaryProtocol proto = new TBinaryProtocol(mb);


    DemoMessage data = new DemoMessage();
    data.read(proto);

    System.out.println(data);

} catch (TException e) {
    e.printStackTrace();
}