/
cache.go
79 lines (69 loc) · 1.7 KB
/
cache.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package cccache
import (
"context"
"github.com/crosect/cc-go/log"
"github.com/eko/gocache/v2/cache"
"github.com/eko/gocache/v2/store"
"time"
)
type Cache struct {
properties *CacheProperties
cache *cache.Cache
}
func NewCache(properties *CacheProperties) (*Cache, error) {
cacheStore, err := NewStore(properties)
if err != nil {
return nil, err
}
c := cache.New(cacheStore)
return &Cache{
properties: properties,
cache: c,
}, nil
}
func (c *Cache) Exist(key string) bool {
_, err := c.Get(key)
return err == nil
}
func (c *Cache) Remember(key string, duration time.Duration, fn func() (interface{}, error)) (interface{}, error) {
value, err := c.Get(key)
if err == nil {
return value, nil
}
v, err := fn()
if err == nil {
c.AsyncSet(key, v, duration)
}
return v, err
}
func (c *Cache) AsyncSet(key string, value interface{}, duration time.Duration) {
go func() {
err := c.cache.Set(context.Background(), key, value, &store.Options{
Expiration: duration,
})
if err != nil {
log.Warnf("cache: async set: %v", err)
}
}()
}
func (c *Cache) Get(key string) (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
value, err := c.cache.Get(ctx, key)
if err != nil {
log.Debugf("cache: get by key: %v: %v", key, err)
return nil, err
}
return value, nil
}
func (c *Cache) Set(key string, value interface{}, duration time.Duration) error {
return c.cache.Set(context.Background(), key, value, &store.Options{
Expiration: duration,
})
}
func (c *Cache) Delete(key string) error {
return c.cache.Delete(context.Background(), key)
}
func (c *Cache) Clear() error {
return c.cache.Clear(context.Background())
}