Created
May 15, 2020 22:43
-
-
Save 178inaba/a618a2a091d4cf64cffd1b8e32cc32be to your computer and use it in GitHub Desktop.
Testing cache mechanism using gob encoding and Redis. Version 2.
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" | |
"os" | |
"time" | |
"github.com/gomodule/redigo/redis" | |
) | |
type User struct { | |
Name string | |
Age int | |
Address string | |
} | |
func main() { | |
r := NewRepository(&redis.Pool{ | |
DialContext: func(ctx context.Context) (redis.Conn, error) { | |
return redis.Dial("tcp", "localhost:6379") | |
}, | |
MaxIdle: 1024, | |
IdleTimeout: 5 * time.Minute, | |
}) | |
ctx := context.Background() | |
// Save | |
userName := os.Args[1] | |
u := User{Name: userName, Age: 25, Address: "Tokyo"} | |
r.setCache(ctx, fmt.Sprintf("user_%s", userName), u) | |
// Reset | |
u = User{} | |
// Load | |
var loadUser User | |
r.getCache(ctx, fmt.Sprintf("user_%s", userName), &loadUser) | |
fmt.Printf("%+v\n", loadUser) | |
} | |
type Repository struct { | |
pool *redis.Pool | |
} | |
func NewRepository(pool *redis.Pool) *Repository { | |
return &Repository{pool: pool} | |
} | |
func (r *Repository) getCache(ctx context.Context, key string, v interface{}) error { | |
conn, err := r.pool.GetContext(ctx) | |
if err != nil { | |
return fmt.Errorf("get redis connection: %w", err) | |
} | |
defer conn.Close() | |
bs, err := redis.Bytes(conn.Do("GET", key)) | |
if err != nil { | |
return fmt.Errorf("get bytes: %w", err) | |
} | |
reader := bytes.NewReader(bs) | |
if err := gob.NewDecoder(reader).Decode(v); err != nil { | |
return fmt.Errorf("decode gob: %w", err) | |
} | |
return nil | |
} | |
func (r *Repository) setCache(ctx context.Context, key string, v interface{}) error { | |
conn, err := r.pool.GetContext(ctx) | |
if err != nil { | |
return fmt.Errorf("get redis connection: %w", err) | |
} | |
defer conn.Close() | |
var buf bytes.Buffer | |
if err := gob.NewEncoder(&buf).Encode(v); err != nil { | |
return fmt.Errorf("encode gob: %w", err) | |
} | |
if _, err := conn.Do("SET", key, buf.Bytes()); err != nil { | |
return fmt.Errorf("set bytes: %w", err) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment