Go语言消息序列化 JSON、ProtoBuf与MsgPack对比
更新时间:2026年05月10日 11:54:36 作者:码龙大大
本文对比了三种序列化方式的特点和Go语言实现,开发者应根据具体场景选择合适的序列化方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
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,name=topic"`
Key string `protobuf:"bytes,2,opt,name=key"`
Value []byte `protobuf:"bytes,3,opt,name=value"`
Timestamp int64 `protobuf:"varint,4,opt,name=timestamp"`
}
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. 序列化对比
| 特性 | JSON | ProtoBuf | MsgPack |
|---|---|---|---|
| 体积 | 大 | 小 | 中 |
| 速度 | 慢 | 快 | 快 |
| 可读性 | 好 | 差 | 差 |
| 跨语言 | 好 | 好 | 好 |
| Schema | 无 | 有 | 无 |
6. 总结
本文对比了三种序列化方式的特点和Go语言实现,开发者应根据具体场景选择合适的序列化方式。
到此这篇关于Go语言消息序列化 JSON、ProtoBuf与MsgPack对比的文章就介绍到这了,更多相关Go语言 JSON ProtoBuf MsgPack内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Golang报“import cycle not allowed”错误的2种解决方法
这篇文章主要给大家介绍了关于Golang报"import cycle not allowed"错误的2种解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以们下面随着小编来一起看看吧2018-08-08


最新评论