thrift 网络栈
英文原版:https://thrift.apache.org/docs/concepts.html
1、thrift 网络栈的简单表示(包括以下四层)
server
processor
protocol
transport
+-------------------------------------------+
| Server |
| (single-threaded, event-driven etc) |
+-------------------------------------------+
| Processor |
| (compiler generated) |
+-------------------------------------------+
| Protocol |
| (JSON, compact etc) |
+-------------------------------------------+
| Transport |
| (raw TCP, HTTP etc) |
+-------------------------------------------+
1、Transport
传输层提供了一个对网络数据读写的抽象,这能够让thrift解耦基础传输和系统的其他部分(比如说序列化和反序列化等)。传输层暴露了以下一些methods:
open
close
read
write
flush
除了以上的传输接口之外,thrift还提供了一个ServerTransport接口来创建和接受原始传输对象。如ServerTransport的名字所示,它主要是用在server端来为传入链接创建新的传输对象。
open
close
accept
listen
以下是大多数的thrift支持的语言可以采用的传输方式:
file: read/write to/from a file on disk
http: as the name suggests
从磁盘读取文件和用http协议传输数据
2、Protocol
Protocl抽象定义了一个机制,这个机制就是能够将内存中的数据结构映射为wire结构,换句话说,protocol指定了底层的transport如何来对数据类型进行编解码,因此protocol实现了编解码范式和负责任的序列化工作。
从这个意义上讲,协议的一些示例包括JSON,XML,纯文本,紧凑二进制等。
以下是protocol层提供的一些接口:
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()
thrift的protocol是面向流设计的,因此他不需要任何显示的框架,比如说没有必要在我们序列化之前知道一个string的长度或者一个list的item个数,thrift支持的语言的主要protocol包括:
binary: Fairly simple binary encoding – the length and type of a field are encoded as bytes followed by the actual value of the field.
binary: 相当简单的二进制编码----一个字段的类型和长度被编码成字节,后面是这个字段的真实值。
compact: Described in THRIFT-110
json
3、processor
一个processor封装了从输入流中读取数据和写数据到输出流的能力,输入输出流表示的是protocol对象。processor的接口也十分简单:
interface TProcessor {
bool process(TProtocol in, TProtocol out) throws TException
}
具体服务的processor的实现是有thrift的编译器来实现的,processor实质上是从wire结构中读取数据,将处理委托给处理程序handler(用户实现的)并写入response数据到wire中
4、server
server集合了以上讨论的所有功能
创建一个transport
为transport创建一个input/output协议
基于input/output协议创建一个processor
等待传入的链接并交个processor