msgp是golang用来做序列化的一个工具
获取方式:
go get github.com/tinylib/msgp
以官网例子来看
wujingcideMacBook-Pro:msgp wujingci$ cat my_types.go
package main
type Person struct {
Name string `msg:"name"`
Address string `msg:"address"`
Age int `msg:"age"`
Hidden string `msg:"-"` // this field is ignored
unexported bool // this field is also ignored
}
wujingcideMacBook-Pro:msgp wujingci$ msgp -file=my_types.go
======== MessagePack Code Generator =======
>>> Input: "my_types.go"
my_types.go: Person: Hidden: ignored.
>>> Wrote and formatted "my_types_gen_test.go"
>>> Wrote and formatted "my_types_gen.go"
wujingcideMacBook-Pro:msgp wujingci$ ls
my_types.go my_types_gen.go my_types_gen_test.go
my_types_gen.go就是生成出来的代码
包含EncodeMsg, DecodeMsg, MarshalMsg, UnmarshalMsg
我们常常会用marshal出来的结果去存redis,这时候我们就发现生成代码里
func (z Person) MarshalMsg(b []byte) (o []byte, err error) {
o = msgp.Require(b, z.Msgsize())
// map header, size 3
// string "name"
o = append(o, 0x83, 0xa4, 0x6e, 0x61, 0x6d, 0x65)
o = msgp.AppendString(o, z.Name)
// string "address"
o = append(o, 0xa7, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73)
o = msgp.AppendString(o, z.Address)
// string "age"
o = append(o, 0xa3, 0x61, 0x67, 0x65)
o = msgp.AppendInt(o, z.Age)
return
}
所有的key都会被塞入,而我们实际上为了节约空间,有些默认值或者空值是不需要插入的,这样就造成了大量的空间浪费。