9
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golangで、MessagePackを使い、Redisに書き込み/読み込みをする

Posted at

下記の書籍の4章のsprinkleを写経中に思い付いたので、やってみた。
「Go言語によるWebアプリケーション開発」
http://www.amazon.co.jp/exec/obidos/ASIN/4873117526/noimpslmtbrk-22/

ライブラリ選定基準は、スターの数やQiitaの記事を参考に選んだ。

Redisへの接続ライブラリはRedigoを使用。
https://github.com/garyburd/redigo

MessagePackのEncode/Decodeライブラリはugorji/goを使用。
https://github.com/ugorji/go

MsgPackToRedis.go
package main

import (
	"github.com/ugorji/go/codec"
	"log"
	"github.com/garyburd/redigo/redis"
	"os"
)

type OtherWord struct {
	Word []string
}

const otherWord = "*"

var transforms = []string{
	otherWord,
	otherWord,
	otherWord,
	otherWord,
	otherWord + "app",
	otherWord + "site",
	otherWord + "time",
	"get" + otherWord,
	"go" + otherWord,
	"lets" + otherWord,
}

//msgpack専用のBundle
var (
	mh codec.MsgpackHandle
)
const message = "length of %#v as MessagePack: %d\n%v"
func main() {
	otherWord := OtherWord{
		Word:transforms,
	}

	writeRedisForUseMsgPack("otherWords", messagePackEncoding(otherWord))

	value := readRedisForUseMsgPack("otherWords")

	messagePackDecoding(value)
}

func messagePackEncoding(otherWord OtherWord) []byte {
	//Encodingされる中身を受け取るbyte[]のスライス
	buf := make([]byte, 0, 64)
	//messagePack専用のBundleを使用してEncoderの準備をして、Encodeする。
	err := codec.NewEncoderBytes(&buf, &mh).Encode(otherWord)
	if err != nil {
		log.Printf("error encoding %v to MessagePack: %v", otherWord, err)
	}
	log.Printf(message, otherWord, len(buf), buf)
	return buf;
}

func messagePackDecoding(buf []byte) OtherWord {
	//Encodingされる中身を受け取るOtherWord構造体型の変数
	var otherWord OtherWord
	//messagePack専用のBundleを使用してDecoderの準備をして、Decodeする。
	err := codec.NewDecoderBytes(buf, &mh).Decode(&otherWord)
	if err != nil {
		log.Printf("error decoding %v to MessagePack: %v", buf, err)
	}
	log.Printf(message, otherWord, len(buf), buf)
	return otherWord;
}

func writeRedisForUseMsgPack(key string, buf []byte) {
	con, err := redis.Dial("tcp", ":6379")
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	defer con.Close()

	con.Do("SET", key, buf)
}

func readRedisForUseMsgPack(key string) []byte {
	con, err := redis.Dial("tcp", ":6379")
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	defer con.Close()

	buf, err := redis.Bytes(con.Do("GET", key))
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	return buf;
}

9
12
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
9
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?