-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.go
59 lines (48 loc) · 931 Bytes
/
simple.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/go-redis/cache/v8"
"github.com/go-redis/redis/v8"
)
type User struct {
ID int
Name string
}
func main() {
ring := redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"server1": ":6379",
"server2": ":6380",
},
})
codec := &cache.Codec{
Redis: ring,
Marshal: func(v interface{}) ([]byte, error) {
return json.Marshal(v)
},
Unmarshal: func(b []byte, v interface{}) error {
return json.Unmarshal(b, v)
},
}
user := &User{
ID: 42,
Name: "John Smith",
}
ctx := context.Background()
if err := codec.Set(&cache.Item{
Ctx: ctx,
Key: fmt.Sprintf("user:%d", user.ID),
Value: user,
TTL: time.Hour,
}); err != nil {
panic(err)
}
var savedUser User
if err := codec.Get(ctx, fmt.Sprintf("user:%d", user.ID), &savedUser); err != nil {
panic(err)
}
fmt.Printf("%+v\n", savedUser)
}