golang gencode 序列化/反序列化数据

栏目: Go · 发布时间: 8年前

内容简介:golang gencode 序列化/反序列化数据

andyleap/gencode 是一个快速的且体积很小的序列化库,速度是标准库10x倍。

首先定义数据结构:test.schema

struct Person {
    Name string
    Age uint8
}

然后通过gencode 命令行生成test.schema.gen.go:

$ gencode go -schema test.schema -package main

下面是结合bolt 来存储数据:

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/boltdb/bolt"
)

func main() {

    db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    db.Update(func(tx *bolt.Tx) error {
        _, err := tx.CreateBucketIfNotExists([]byte("person"))
        if err != nil {
            return err
        }
        return nil
    })

    person := Person{
        Name: "testname",
        Age:  20,
    }

    db.Update(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("person"))

        buf, _ := person.Marshal(nil)
        fmt.Println(buf, string(buf))
        b.Put([]byte(person.Name), buf)

        fmt.Printf("Gencode encoded size: %v\n", len(buf))

        return nil
    })

    db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("person"))

        if err := b.ForEach(func(k, v []byte) error {
            fmt.Printf("%s is %s.\n", k, v)
            p := Person{}
            p.Unmarshal(v)
            fmt.Println(p)
            return nil
        }); err != nil {
            return err
        }

        return nil
    })

}

输出:

[8 116 101 115 116 110 97 109 101 20]testname
Gencode encoded size: 10
testname istestname.
{testname 20}

因为 gencode 不会写入字段的名字,所以体积很小,正因为如此,用gencode 序列化和反序列化数据时应该注意,数据结构不能动态改变。

项目地址 andyleap/gencode 1


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Philosophy of Software Design

A Philosophy of Software Design

John Ousterhout / Yaknyam Press / 2018-4-6 / GBP 14.21

This book addresses the topic of software design: how to decompose complex software systems into modules (such as classes and methods) that can be implemented relatively independently. The book first ......一起来看看 《A Philosophy of Software Design》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具