Go语言消息序列化:JSON、ProtoBuf与MsgPack对比

发布时间:2026/7/17 7:09:54

Go语言消息序列化:JSON、ProtoBuf与MsgPack对比 Go语言消息序列化JSON、ProtoBuf与MsgPack对比1. 序列化重要性消息队列中序列化方式直接影响消息体积、传输效率和易用性。常用的序列化方式包括JSON、Protocol Buffers和MessagePack。2. JSON序列化type JSONSerializer struct{} func (s *JSONSerializer) Serialize(v interface{}) ([]byte, error) { return json.Marshal(v) } func (s *JSONSerializer) Deserialize(data []byte, v interface{}) error { return json.Unmarshal(data, v) } type JSONMessage struct { Topic string Key string Value interface{} } func (j *JSONMessage) Serialize() ([]byte, error) { return json.Marshal(j) } func DeserializeJSONMessage(data []byte) (*JSONMessage, error) { var msg JSONMessage err : json.Unmarshal(data, msg) if err ! nil { return nil, err } return msg, nil }3. Protocol Buffers序列化syntax proto3; package message; option go_package ./;message; message Person { string name 1; int32 age 2; string email 3; } message Message { string topic 1; string key 2; bytes value 3; int64 timestamp 4; } message BatchMessage { repeated Message messages 1; }package protobuf import ( fmt github.com/golang/protobuf/proto ) type ProtoSerializer struct{} func (s *ProtoSerializer) Serialize(v proto.Message) ([]byte, error) { return proto.Marshal(v) } func (s *ProtoSerializer) Deserialize(data []byte, v proto.Message) error { return proto.Unmarshal(data, v) } type Message struct { Topic string protobuf:bytes,1,opt,nametopic Key string protobuf:bytes,2,opt,namekey Value []byte protobuf:bytes,3,opt,namevalue Timestamp int64 protobuf:varint,4,opt,nametimestamp } func (m *Message) Reset() {} func (m *Message) String() string { return fmt.Sprintf(%v, *m) } func (m *Message) ProtoMessage() {}4. MessagePack序列化package msgpack import ( github.com/vmihailenco/msgpack/v5 ) type MsgPackSerializer struct{} func (s *MsgPackSerializer) Serialize(v interface{}) ([]byte, error) { return msgpack.Marshal(v) } func (s *MsgPackSerializer) Deserialize(data []byte, v interface{}) error { return msgpack.Unmarshal(data, v) } type Message struct { Topic string Key string Value []byte Timestamp int64 } func (m *Message) Encode() ([]byte, error) { return msgpack.Marshal(m) } func DecodeMessage(data []byte) (*Message, error) { var m Message err : msgpack.Unmarshal(data, m) if err ! nil { return nil, err } return m, nil }5. 序列化对比特性JSONProtoBufMsgPack体积大小中速度慢快快可读性好差差跨语言好好好Schema无有无6. 总结本文对比了三种序列化方式的特点和Go语言实现开发者应根据具体场景选择合适的序列化方式。

相关新闻