前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用easyjson提高序列化传输的效率

使用easyjson提高序列化传输的效率

原创
作者头像
Johns
修改2022-06-30 10:32:28
1.9K0
修改2022-06-30 10:32:28
举报
文章被收录于专栏:代码工具代码工具

介绍

easyjson 是用来快速进行json序列化与反序列化的工具包,通过给我们要进行序列化的struct生成方法来实现不通过反射进行json序列化,比golang原有json工具包,性能能够提高2~3倍。

go 语言的反射api的设计不像java一样可以直接获取对象的字段值, 而是每次要使用reflect.ValueOf(v) 来先创建一个新的字段对象再获取字段值, 这会额外增加GC的负担,同时效率也低。通过遍历字段进行字段内容拼装可以避免不必要的对象创建, 且效率上也会更高。

使用

  • 安装
代码语言:txt
复制
go get -u github.com/mailru/easyjson/
go install  github.com/mailru/easyjson/easyjsonor
go build -o easyjson github.com/mailru/easyjson/easyjson

检查是否安装成功

代码语言:txt
复制
 ~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
.....
  • 实体类 service.go
代码语言:txt
复制
//easyjson:json
type MultiplyRequest struct {
	A int `json:"a"`
	B int `json:"b"`
}

//easyjson:json
type MultiplyResponse struct {
	Res int `json:"res"`
}
  • 进入命令行, 切换到当前go文件所在目录输入:easyjson -all service.go会生成service_easyjson.go,该文件提供了序列化和反序列化的方法。
代码语言:txt
复制
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的具体过程。

  • 正式代码替换 transport.go
代码语言:txt
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档