-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_with_subcache.go
79 lines (67 loc) · 1.7 KB
/
cache_with_subcache.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 cachier
import "reflect"
// CacheWithSubcache is a Cache with L1 subcache.
type CacheWithSubcache[T any] struct {
Cache *Cache[T]
Subcache *Cache[T]
}
// Get gets a cached value by key
func (cs *CacheWithSubcache[T]) Get(key string) (interface{}, error) {
value, err := cs.Subcache.GetOrCompute(key, func() (*T, error) {
return cs.Cache.Get(key)
})
return *value, err
}
// Peek gets a cached key value without side-effects (i.e. without adding to L1 cache)
func (cs *CacheWithSubcache[T]) Peek(key string) (interface{}, error) {
value, err := cs.Subcache.Peek(key)
if err == nil {
return value, err
}
return cs.Cache.Peek(key)
}
// Set stores a key-value pair into cache
func (cs *CacheWithSubcache[T]) Set(key string, value interface{}) error {
var typedValue *T
if reflect.ValueOf(value).Kind() == reflect.Ptr {
value, ok := value.(*T)
if !ok {
return ErrWrongDataType
}
typedValue = value
} else {
value, ok := value.(T)
if !ok {
return ErrWrongDataType
}
typedValue = &value
}
if err := cs.Subcache.Set(key, typedValue); err != nil {
return err
}
return cs.Cache.Set(key, typedValue)
}
// Delete removes a key from cache
func (cs *CacheWithSubcache[T]) Delete(key string) error {
if err := cs.Cache.Delete(key); err != nil {
return err
}
return cs.Subcache.Delete(key)
}
// Keys returns a slice of all keys in the cache
func (cs *CacheWithSubcache[T]) Keys() ([]string, error) {
return cs.Cache.Keys()
}
// Purge removes all the records from the cache
func (cs *CacheWithSubcache[T]) Purge() error {
keys, err := cs.Keys()
if err != nil {
return err
}
for _, key := range keys {
if err := cs.Delete(key); err != nil {
return err
}
}
return nil
}