forked from viney-shih/go-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_setandget_test.go
65 lines (53 loc) · 1.27 KB
/
example_setandget_test.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
60
61
62
63
64
65
package cache_test
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/viney-shih/go-cache"
)
type Object struct {
Str string
Num int
}
func Example_setAndGetPattern() {
tinyLfu := cache.NewTinyLFU(10000)
rds := cache.NewRedis(redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"server1": ":6379",
},
}))
cacheF := cache.NewFactory(rds, tinyLfu)
// We create a group of cache named "set-and-get".
// It uses the shared cache only with TTL of ten seconds.
c := cacheF.NewCache([]cache.Setting{
{
Prefix: "set-and-get",
CacheAttributes: map[cache.Type]cache.Attribute{
cache.SharedCacheType: {TTL: 10 * time.Second},
},
},
})
ctx := context.TODO()
// set the cache
obj := &Object{
Str: "value1",
Num: 1,
}
if err := c.Set(ctx, "set-and-get", "key", obj); err != nil {
panic("not expected")
}
// read the cache
container := &Object{}
if err := c.Get(ctx, "set-and-get", "key", container); err != nil {
panic("not expected")
}
fmt.Println(container) // Object{ Str: "value1", Num: 1}
// read the cache but failed
if err := c.Get(ctx, "set-and-get", "no-such-key", container); err != nil {
fmt.Println(err) // errors.New("cache key is missing")
}
// Output:
// &{value1 1}
// cache key is missing
}