-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbigcache.go
More file actions
53 lines (45 loc) · 1.09 KB
/
bigcache.go
File metadata and controls
53 lines (45 loc) · 1.09 KB
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
package bigcache
import (
"encoding/json"
"time"
"github.com/allegro/bigcache"
"github.com/easy-cache/cache"
)
type bigCacheDriver struct {
bigcache *bigcache.BigCache
}
func (bcd bigCacheDriver) Get(key string) ([]byte, bool, error) {
bs, err := bcd.bigcache.Get(key)
if err != nil {
if err == bigcache.ErrEntryNotFound {
return nil, false, nil
}
return nil, false, err
}
var item cache.Item
if err = json.Unmarshal(bs, &item); err != nil {
return nil, false, err
}
val, ok := item.GetValue()
if ok == false {
_ = bcd.Del(key)
}
return val, ok, err
}
func (bcd bigCacheDriver) Set(key string, val []byte, ttl time.Duration) error {
item := cache.NewItem(val, ttl)
bs, err := json.Marshal(item)
if err == nil {
err = bcd.bigcache.Set(key, bs)
}
return err
}
func (bcd bigCacheDriver) Del(key string) error {
return bcd.bigcache.Delete(key)
}
func NewDriver(bc *bigcache.BigCache) cache.DriverInterface {
return bigCacheDriver{bigcache: bc}
}
func NewCache(bc *bigcache.BigCache, args ...interface{}) cache.Interface {
return cache.New(append(args, NewDriver(bc))...)
}