This repository has been archived by the owner on Feb 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
cache.go
84 lines (76 loc) · 1.63 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
80
81
82
83
84
package ttlcache
import (
"sync"
"time"
)
// Cache is a synchronised map of items that auto-expire once stale
type Cache struct {
mutex sync.RWMutex
ttl time.Duration
items map[string]*Item
}
// Set is a thread-safe way to add new items to the map
func (cache *Cache) Set(key string, data string) {
cache.mutex.Lock()
item := &Item{data: data}
item.touch(cache.ttl)
cache.items[key] = item
cache.mutex.Unlock()
}
// Get is a thread-safe way to lookup items
// Every lookup, also touches the item, hence extending it's life
func (cache *Cache) Get(key string) (data string, found bool) {
cache.mutex.Lock()
item, exists := cache.items[key]
if !exists || item.expired() {
data = ""
found = false
} else {
item.touch(cache.ttl)
data = item.data
found = true
}
cache.mutex.Unlock()
return
}
// Count returns the number of items in the cache
// (helpful for tracking memory leaks)
func (cache *Cache) Count() int {
cache.mutex.RLock()
count := len(cache.items)
cache.mutex.RUnlock()
return count
}
func (cache *Cache) cleanup() {
cache.mutex.Lock()
for key, item := range cache.items {
if item.expired() {
delete(cache.items, key)
}
}
cache.mutex.Unlock()
}
func (cache *Cache) startCleanupTimer() {
duration := cache.ttl
if duration < time.Second {
duration = time.Second
}
ticker := time.Tick(duration)
go (func() {
for {
select {
case <-ticker:
cache.cleanup()
}
}
})()
}
// NewCache is a helper to create instance of the Cache struct
func NewCache(duration time.Duration) *Cache {
cache := &Cache{
ttl: duration,
items: map[string]*Item{},
}
cache.startCleanupTimer()
return cache
}