|
| 1 | +/* |
| 2 | +消息编解码 |
| 3 | +
|
| 4 | +定义二进制协议格式(参考Kafka) |
| 5 | +处理压缩(Snappy) |
| 6 | +*/ |
| 7 | +package protocol |
| 8 | + |
| 9 | +import ( |
| 10 | + "bytes" |
| 11 | + "encoding/binary" |
| 12 | + "ryanMQ/internal/utils/log" |
| 13 | + |
| 14 | + "github.com/golang/snappy" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + ProduceRequestType = byte(0x01) |
| 19 | + FetchRequestType = byte(0x02) |
| 20 | + OffsetCommitType = byte(0x03) |
| 21 | + TopicMetadataRequestType = byte(0x04) |
| 22 | +) |
| 23 | + |
| 24 | +func EncodeProduceRequest(req *ProduceRequest) ([]byte, error) { |
| 25 | + buf := new(bytes.Buffer) //写入缓冲区 |
| 26 | + |
| 27 | + //主题 :2 字节长度(int16类型) + 数据 |
| 28 | + topicBytes := []byte(req.Topic) |
| 29 | + //大端字节序存储 |
| 30 | + if err := binary.Write(buf, binary.BigEndian, int16(len(topicBytes))); err != nil { |
| 31 | + return nil, err |
| 32 | + } |
| 33 | + buf.Write(topicBytes) |
| 34 | + |
| 35 | + //分区号:4字节 |
| 36 | + binary.Write(buf, binary.BigEndian, req.Partition) |
| 37 | + |
| 38 | + //消息列表 (每条消息: 4字节 长度(len) + 数据) |
| 39 | + for _, msg := range req.Messages { |
| 40 | + binary.Write(buf, binary.BigEndian, int32(len(msg))) |
| 41 | + buf.Write(msg) |
| 42 | + } |
| 43 | + |
| 44 | + //构建最终请求(添加请求头和长度) |
| 45 | + header := RequestHeader{ |
| 46 | + Length: int32(buf.Len()), |
| 47 | + RequestType: ProduceRequestType, //生产者请求 |
| 48 | + } |
| 49 | + headerBytes, err := encodeHeader(header) |
| 50 | + if err != nil { |
| 51 | + log.Error("encode header error: %v", err) |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + |
| 55 | + return append(headerBytes, buf.Bytes()...), nil |
| 56 | +} |
| 57 | + |
| 58 | +func encodeHeader(header RequestHeader) ([]byte, error) { |
| 59 | + buf := new(bytes.Buffer) |
| 60 | + |
| 61 | + if err := binary.Write(buf, binary.BigEndian, header.Length); err != nil { |
| 62 | + return nil, err |
| 63 | + } |
| 64 | + |
| 65 | + if err := binary.Write(buf, binary.BigEndian, header.RequestType); err != nil { |
| 66 | + return nil, err |
| 67 | + } |
| 68 | + |
| 69 | + return buf.Bytes(), nil |
| 70 | +} |
| 71 | + |
| 72 | +func DecodeProduceRequest(data []byte) (*ProduceRequest, error) { |
| 73 | + buf := bytes.NewBuffer(data) |
| 74 | + req := &ProduceRequest{} |
| 75 | + |
| 76 | + //解析请求头 |
| 77 | + |
| 78 | +} |
| 79 | + |
| 80 | +func EncodeConsumeRequest() |
| 81 | + |
| 82 | +func CompressWithSnappy(data []byte) ([]byte, error) { |
| 83 | + return snappy.Encode(nil, data), nil |
| 84 | +} |
| 85 | + |
| 86 | +func DecompressWithSnappy(data []byte) ([]byte, error) { |
| 87 | + return snappy.Decode(nil, data) |
| 88 | +} |
0 commit comments