LoginSignup
3
1

More than 5 years have passed since last update.

GolangでMessagePackでシリアライズした構造体をAerospikeに保存する

Last updated at Posted at 2017-05-30

コード

package main

import (
    "fmt"

    as "github.com/aerospike/aerospike-client-go"
    "github.com/ugorji/go/codec"
)

type Human struct {
    Name struct {
        First string
        Last  string
    }
    Age int
}

// MessagePackでシリアライズしてAerospikeに保存
func put() {
    ieyasu := &Human{
        Name: struct {
            First string
            Last  string
        }{
            "Ieyasu",
            "Tokugawa",
        },
        Age: 70,
    }

    var buf []byte
    mh := &codec.MsgpackHandle{RawToString: true}
    codec.NewEncoderBytes(&buf, mh).Encode(ieyasu)

    client, _ := as.NewClient("localhost", 3000)
    key, _ := as.NewKey("bar", "set", "key")
    bins := as.BinMap{"selialized": buf}

    client.Put(nil, key, bins)
}

// Aerospikeから取得したデータをMessagePackでデシリアライズして表示
func get() {
    client, _ := as.NewClient("localhost", 3000)
    key, _ := as.NewKey("bar", "set", "key")
    res, _ := client.Get(nil, key)

    var human Human
    mh := codec.MsgpackHandle{RawToString: true}
    codec.NewDecoderBytes(res.Bins["selialized"].([]uint8), &mh).Decode(&human)

    fmt.Println(human)
}

func main() {
    put()
    get()
}

実行結果

{{Ieyasu Tokugawa} 70}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1