forked from microsoftarchive/ttlcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
93 lines (77 loc) · 1.69 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
85
86
87
88
89
90
91
92
93
package ttlcache
import (
"sync"
"time"
)
// Cache is a synchronised map of items that auto-expire once stale
type Cache struct {
sync.RWMutex
ttl time.Duration
items map[string]*Item
}
// NewCache is a helper to create instance of the Cache struct
func New(duration time.Duration) *Cache {
cache := &Cache{
ttl: duration,
items: make(map[string]*Item, 0),
}
cache.startEvictionTimer()
return cache
}
// Set is a thread-safe way to add new items to the map
func (cache *Cache) Set(key string, data []byte) {
cache.Lock()
defer cache.Unlock()
item := &Item{data: data}
item.touch(cache.ttl)
cache.items[key] = item
}
// 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) ([]byte, bool) {
cache.Lock()
defer cache.Unlock()
item, exists := cache.items[key]
if !exists || item.expired() {
return nil, false
}
item.touch(cache.ttl)
return item.data, true
}
// Evict offers a thread-safe way to evict a cache item by key.
func (cache *Cache) Evict(key string) {
cache.Lock()
defer cache.Unlock()
delete(cache.items, key)
}
// Count returns the number of items in the cache
func (cache *Cache) Count() int {
cache.RLock()
defer cache.RUnlock()
count := len(cache.items)
return count
}
func (cache *Cache) startEvictionTimer() {
duration := cache.ttl
if duration < time.Second {
duration = time.Second
}
ticker := time.Tick(duration)
go func() {
for {
select {
case <-ticker:
cache.evict()
}
}
}()
}
func (cache *Cache) evict() {
cache.Lock()
defer cache.Unlock()
for key, item := range cache.items {
if item.expired() {
delete(cache.items, key)
}
}
}