-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttlcache.go
77 lines (68 loc) · 1.53 KB
/
ttlcache.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
package ttlcache
// stdlib
import (
"errors"
"sync"
"time"
)
// ERR_KEY_NO_EXISTS is the error if an expected key is not present
var ERR_KEY_NO_EXISTS = errors.New("TTLCache: Key doesn't exist")
// NewTTLCache creates a ttl cache with a default duration
func NewTTLCache(defaultTTL time.Duration) *TTLCache {
return &TTLCache{
defaultTTL: defaultTTL,
keys: map[string]interface{}{},
}
}
// TTLCache stores the cache state
type TTLCache struct {
sync.Mutex
defaultTTL time.Duration
keys map[string]interface{}
}
// Exists checks if a key is in the cache
func (c *TTLCache) Exists(key string) bool {
c.Lock()
defer c.Unlock()
_, ok := c.keys[key]
return ok
}
// Get the value at a key
func (c *TTLCache) Get(key string) (interface{}, error) {
c.Lock()
defer c.Unlock()
if _, ok := c.keys[key]; !ok {
return nil, ERR_KEY_NO_EXISTS
}
return c.keys[key], nil
}
// Set sets a key with the default ttl
func (c *TTLCache) Set(key string, value interface{}) error {
c.Lock()
defer c.Unlock()
c.keys[key] = value
time.AfterFunc(c.defaultTTL, func() {
c.Expire(key)
})
return nil
}
// SetEx sets a key with a specific ttl
func (c *TTLCache) SetEx(key string, value interface{}, expireAt time.Duration) error {
c.Lock()
defer c.Unlock()
c.keys[key] = value
time.AfterFunc(expireAt, func() {
c.Expire(key)
})
return nil
}
// Expire a key immediately
func (c *TTLCache) Expire(key string) error {
c.Lock()
defer c.Unlock()
if _, ok := c.keys[key]; !ok {
return ERR_KEY_NO_EXISTS
}
delete(c.keys, key)
return nil
}