-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
71 lines (57 loc) · 1.13 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
package cachemap
import (
"log"
"sync"
"time"
)
type Store struct {
ttl int64
cache map[string]interface{}
sync.RWMutex
}
type Option struct {
TTL int64
}
func New(o *Option) *Store {
return &Store{ttl: o.TTL, cache: make(map[string]interface{}, 0)}
}
type CacheObject struct {
key string
store *Store
ttl int64
}
type CacheObjectOption struct {
TTL int64
}
func (s *Store) NewCacheObject(key string, option ...CacheObjectOption) *CacheObject {
ttl := s.ttl
if len(option) > 0 {
ttl = option[0].TTL
}
return &CacheObject{key: key, store: s, ttl: ttl}
}
func (c *CacheObject) Get() (interface{}, bool) {
c.store.Lock()
defer c.store.Unlock()
value, ok := c.store.cache[c.key]
return value, ok
}
func (c *CacheObject) Set(val interface{}) {
c.store.Lock()
defer c.store.Unlock()
c.store.cache[c.key] = val
c.setttl()
}
func (c *CacheObject) Expire() {
c.store.Lock()
defer c.store.Unlock()
delete(c.store.cache, c.key)
}
func (c *CacheObject) setttl() {
t := time.NewTicker(time.Second * time.Duration(c.ttl))
go func() {
<-t.C
c.Expire()
log.Printf("key `%v` evicted after %vs", c.key, c.ttl)
}()
}