-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcache.go
60 lines (53 loc) · 1.04 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
package pool
import (
"sync"
"time"
)
// Cache - caches nodes by session ID.
// !!! no thread safe
type Cache struct {
storage map[string]*cacheEntry
expirationTime time.Duration
sync.RWMutex
}
type cacheEntry struct {
node *Node
created time.Time
}
// NewCache - constructor of Cache.
func NewCache(expirationTime time.Duration) *Cache {
return &Cache{
storage: make(map[string]*cacheEntry),
expirationTime: expirationTime,
}
}
// Set - caches a node.
func (c *Cache) Set(key string, node *Node) {
c.Lock()
c.storage[key] = &cacheEntry{
node: node,
created: time.Now(),
}
c.Unlock()
}
// Get - returns node from cache.
func (c *Cache) Get(key string) (node *Node, ok bool) {
c.RLock()
entry, ok := c.storage[key]
if !ok {
c.RUnlock()
return nil, false
}
c.RUnlock()
return entry.node, true
}
// CleanUp - removes an expired cache.
func (c *Cache) CleanUp() {
c.Lock()
for i := range c.storage {
if time.Since(c.storage[i].created) > c.expirationTime {
delete(c.storage, i)
}
}
c.Unlock()
}