Skip to content

Instantly share code, notes, and snippets.

@178inaba
Created May 15, 2020 22:08
Show Gist options
  • Save 178inaba/c9379a75ca1ca4e74d8ae2fc9664568e to your computer and use it in GitHub Desktop.
Save 178inaba/c9379a75ca1ca4e74d8ae2fc9664568e to your computer and use it in GitHub Desktop.
Testing cache mechanism using gob encoding and Redis.
package main
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"time"
"github.com/gomodule/redigo/redis"
)
type User struct {
Address string
Name string
}
func main() {
pool := &redis.Pool{
DialContext: func(ctx context.Context) (redis.Conn, error) {
return redis.Dial("tcp", "localhost:6379")
},
MaxIdle: 1024,
IdleTimeout: 5 * time.Minute,
}
conn := pool.Get()
defer conn.Close()
u := User{Address: "tokyo", Name: "bob"}
// Save
var buf bytes.Buffer
gob.NewEncoder(&buf).Encode(u)
// Reset
u = User{}
conn.Do("SET", "test", buf.Bytes())
// Load
bs, _ := redis.Bytes(conn.Do("GET", "test"))
bytesReader := bytes.NewReader(bs)
var loadUser User
gob.NewDecoder(bytesReader).Decode(&loadUser)
fmt.Println(loadUser)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment