easyjson 是用来快速进行json序列化与反序列化的工具包,通过给我们要进行序列化的struct生成方法来实现不通过反射进行json序列化,比golang原有json工具包,性能能够提高2~3倍。
go 语言的反射api的设计不像java一样可以直接获取对象的字段值, 而是每次要使用reflect.ValueOf(v) 来先创建一个新的字段对象再获取字段值, 这会额外增加GC的负担,同时效率也低。通过遍历字段进行字段内容拼装可以避免不必要的对象创建, 且效率上也会更高。
go get -u github.com/mailru/easyjson/
go install github.com/mailru/easyjson/easyjsonor
go build -o easyjson github.com/mailru/easyjson/easyjson
检查是否安装成功
~bash>easyjson
Usage of easyjson:
-all
generate marshaler/unmarshalers for all structs in a file
-build_tags string
build tags to add to generated file
-byte
use simple bytes instead of Base64Bytes for slice of bytes
-disable_members_unescape
.....
//easyjson:json
type MultiplyRequest struct {
A int `json:"a"`
B int `json:"b"`
}
//easyjson:json
type MultiplyResponse struct {
Res int `json:"res"`
}
func easyjson8d893851DecodeGoKitMicroservicePb3(in *jlexer.Lexer, out *MultiplyRequest) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeFieldName(false)
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "a":
out.A = int64(in.Int64())
case "b":
out.B = int64(in.Int64())
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}
我们可以非常清晰地看到Marshal的具体过程。
func decodeMultiplyRequest(ctx context.Context, r *http.Request) (interface{}, error) {
bs, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
fmt.Printf(string(bs))
req := &MultiplyRequest{}
err = req.UnmarshalJSON(bs)
if err != nil {
return nil, err
}
return nil, nil
}
func decodeMultiplyRequest(ctx context.Context, r *http.Request) (interface{}, error) {
bs, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
fmt.Printf(string(bs))
req := &MultiplyRequest{}
err = req.UnmarshalJSON(bs)
if err != nil {
return nil, err
}
return nil, nil
}
// decode response
func encodeMultiplyResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
if f, ok := response.(endpoint.Failer); ok && f.Failed() != nil {
errorEncoder(ctx, f.Failed(), w)
return nil
}
resp := response.(*pb.MultiplyResponse)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
bs, err := resp.MarshalJSON()
if err != nil {
return err
}
w.Write(bs)
return nil
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。