Thrift的網路堆疊

C站清道夫_bsj發表於2020-11-03

網路堆疊結構簡圖

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

支援的型別:

示例: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處理

相關文章