NSQ 源码分析之NSQD--消息协议 Message

今天主要讲的是 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 源码实现 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章