Created
May 15, 2020 22:08
-
-
Save 178inaba/c9379a75ca1ca4e74d8ae2fc9664568e to your computer and use it in GitHub Desktop.
Testing cache mechanism using gob encoding and Redis.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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