-
Notifications
You must be signed in to change notification settings - Fork 0
/
polacache.go
120 lines (100 loc) · 1.96 KB
/
polacache.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package polacache
import (
"fmt"
"sync"
"time"
)
type Item struct {
Key string
Value interface{}
}
type cachedItem struct {
item Item
expiresAt int64
}
type cache struct {
stop chan struct{}
wg sync.WaitGroup
lock sync.RWMutex
items map[interface{}]cachedItem
}
// Returns a new polacache, with the given cleanup interval.
//
// Example:
// package main
//
// import "github.com/nowayhecodes/polacache"
//
// cache := polacache.New(1 * time.Minute)
// ...
func New(cleanupInterval time.Duration) *cache {
c := &cache{
items: make(map[interface{}]cachedItem),
stop: make(chan struct{}),
}
c.wg.Add(1)
go func(cleanupInterval time.Duration) {
defer c.wg.Done()
c.cleanupLoop(cleanupInterval)
}(cleanupInterval)
return c
}
// Puts an item in the cache with the given expiration timestamp
//
// Example:
// polacache.Set(item, time.Now().Add(1*time.Hour).Unix())
// ...
func (c *cache) Set(i Item, expiresAt int64) {
c.lock.Lock()
defer c.lock.Unlock()
c.items[i.Key] = cachedItem{
item: i,
expiresAt: expiresAt,
}
}
// Looks up the given key's value in the cache
//
// Example:
// polacache.Get(item.Key)
// ...
func (c *cache) Get(key string) (interface{}, error) {
c.lock.Lock()
defer c.lock.Unlock()
cached, ok := c.items[key]
if !ok {
return Item{}, fmt.Errorf("key %v not in cache", key)
}
return cached.item.Value, nil
}
// Given a key, removes the item from the cache
//
// Example:
// polacache.Delete(item.Key)
// ...
func (c *cache) Delete(key string) {
c.lock.Lock()
defer c.lock.Unlock()
delete(c.items, key)
}
func (c *cache) cleanupLoop(interval time.Duration) {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-c.stop:
return
case <-t.C:
c.lock.Lock()
for uid, cached := range c.items {
if cached.expiresAt <= time.Now().Unix() {
delete(c.items, uid)
}
}
c.lock.Unlock()
}
}
}
func (c *cache) stopCleanup() {
close(c.stop)
c.wg.Wait()
}