网络堆栈结构简图
+-------------------------------------------+
| Server |
| (single-threaded, event-driven etc) |
+-------------------------------------------+
| Processor |
| (compiler generated) |
+-------------------------------------------+
| Protocol |
| (JSON, compact etc) |
+-------------------------------------------+
| Transport |
| (raw TCP, HTTP etc) |
+-------------------------------------------+
Transport
Transport在网络上对读写、收发提供了简单的抽象,例如序列化和反序列化。
通过Transport的接口提供了如下的方法:
- open / close / read / write / flush
ServerTransport
顾名思义,ServerTransport用于server端为新收到的连接创建原始的传输。
- open / listen / accept / close
以下是大多数Thrift支持的语言可用的传输方式:
- file: 文件读写
- http:网络传输
Protocol
抽象定义了一种将内存数据映射为有线格式数的机制,换句话说,协议指定数据类型如何使用基础传输来对自身编码解码。
Thrift的Protocol 面向流设计,无需任何明确的框架,意思就是说在编码解码的时候我们不需要知道数据的长度(string length / list items length)
支持的类型:
- binary
- compat(紧凑数据)
- json
示例:xml json 纯文本 紧凑的二进制
writeMessageBegin(name, type, seq)
writeMessageEnd()
writeStructBegin(name)
writeStructEnd()
writeFieldBegin(name, type, id)
writeFieldEnd()
writeFieldStop()
writeMapBegin(ktype, vtype, size)
writeMapEnd()
writeListBegin(etype, size)
writeListEnd()
writeSetBegin(etype, size)
writeSetEnd()
writeBool(bool)
writeByte(byte)
writeI16(i16)
writeI32(i32)
writeI64(i64)
writeDouble(double)
writeString(string)
name, type, seq = readMessageBegin()
readMessageEnd()
name = readStructBegin()
readStructEnd()
name, type, id = readFieldBegin()
readFieldEnd()
k, v, size = readMapBegin()
readMapEnd()
etype, size = readListBegin()
readListEnd()
etype, size = readSetBegin()
readSetEnd()
bool = readBool()
byte = readByte()
i16 = readI16()
i32 = readI32()
i64 = readI64()
double = readDouble()
string = readString()
Processor
Processor封装了数据读写的输入输出流,输入输出流是Protocol的对象。
接口如下,非常简单
interface TProcessor {
bool process(TProtocol in, TProtocol out) throws TException
}
具体的实现是通过编译器实现,读写数据是通过输入输出流。
Server
服务器将上诉的所有功能汇总
- 创建Transport
- 为Transport创建输入输出流对象(Protocol)
- 为输入输出流(Protocol)创建processor
- 等待连接并且把连接交给Processor处理