今天主要講的是 NSQD 中 消息協議 Message,Message 主要作用是對客戶端發送過來的消息進行Message 封裝,然後等待消費者消費 或者將 Message 轉換爲字節流發送客戶端。
主要代碼文件:
1.nsqd/message.go
Message 結構體
type MessageID [MsgIDLength]byte // 定義消息 ID 類型
type Message struct {
ID MessageID //消息ID
Body []byte //消息實體
Timestamp int64 //發佈時間
Attempts uint16 //嘗試消費次數
// for in-flight handling
deliveryTS time.Time
clientID int64 //客戶端ID
pri int64 //
index int //主要是用於優先級隊列中,定位的索引
deferred time.Duration //延時發佈時間
}
完整的消息協議應該是:
消息總長度(4字節) + 消息類型(4個字節) + m.Timestamp(8個字節) + m.Attempts(2個字節) + m.ID(16個字節) + m.Body(N個字節)
消息類型包括:
frameTypeResponse int32 = 0 正常響應類型
frameTypeError int32 = 1 錯誤響應類型
frameTypeMessage int32 = 2 消息響應類型
WriteTo 函數的作用是 將 Message 內部的 Timestamp、Attempts、ID 和 Body 輸出到指定IO端。
func (m *Message) WriteTo(w io.Writer) (int64, error) {
var buf [10]byte
var total int64
//轉換爲大端字節流( TCP 協議使用的是大端字節流,PC 使用的是小端字節流)
binary.BigEndian.PutUint64(buf[:8], uint64(m.Timestamp))
binary.BigEndian.PutUint16(buf[8:10], uint16(m.Attempts))
//輸出 Timestamp + Attempts
n, err := w.Write(buf[:])
total += int64(n)
if err != nil {
return total, err
}
//輸出 ID
n, err = w.Write(m.ID[:])
total += int64(n)
if err != nil {
return total, err
}
//輸出消息實體
n, err = w.Write(m.Body)
total += int64(n)
if err != nil {
return total, err
}
return total, nil
}
decodeMessage 函數用於解析字節流,轉換爲Message
func decodeMessage(b []byte) (*Message, error) {
var msg Message
if len(b) < minValidMsgLength { //最小消息長度是 ID+Timestamp+Attempts
return nil, fmt.Errorf("invalid message buffer size (%d)", len(b))
}
msg.Timestamp = int64(binary.BigEndian.Uint64(b[:8])) //時間
msg.Attempts = binary.BigEndian.Uint16(b[8:10]) //嘗試次數
copy(msg.ID[:], b[10:10+MsgIDLength]) //消息ID
msg.Body = b[10+MsgIDLength:] //消息實體
return &msg, nil
}
總結:消息協議主要解決的問題是將字節流解析成Message 或將 Message 轉換爲字節流的過程。
下次分享:NSQD 的 Lookup 源碼實現