Total Lines | 103 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package cacheset |
||
2 | |||
3 | import ( |
||
4 | "sync" |
||
5 | "time" |
||
6 | |||
7 | "github.com/memnix/memnix-rest/config" |
||
8 | ) |
||
9 | |||
10 | // Cache is a thread-safe map with expiration times. |
||
11 | // It's used for caching in memory. |
||
12 | type Cache struct { |
||
13 | c map[string]int64 // map of cache items |
||
14 | mu sync.RWMutex // mutex for the map |
||
15 | close chan struct{} |
||
16 | } |
||
17 | |||
18 | // New creates a new cache that asynchronously cleans |
||
19 | // expired entries after the given time passes. |
||
20 | func New() *Cache { |
||
21 | cache := &Cache{ |
||
22 | close: make(chan struct{}), |
||
23 | c: make(map[string]int64), |
||
24 | mu: sync.RWMutex{}, |
||
25 | } |
||
26 | |||
27 | go func() { |
||
28 | ticker := time.NewTicker(config.CleaningInterval) |
||
29 | defer ticker.Stop() |
||
30 | |||
31 | for { |
||
32 | select { |
||
33 | case <-ticker.C: |
||
34 | now := time.Now().UnixNano() |
||
35 | |||
36 | for k, v := range cache.c { |
||
37 | if v > 0 && v < now { |
||
38 | cache.mu.Lock() |
||
39 | delete(cache.c, k) |
||
40 | cache.mu.Unlock() |
||
41 | } |
||
42 | } |
||
43 | |||
44 | case <-cache.close: |
||
45 | return |
||
46 | } |
||
47 | } |
||
48 | }() |
||
49 | |||
50 | return cache |
||
51 | } |
||
52 | |||
53 | // Close stops the cache's cleaning goroutine. |
||
54 | func (c *Cache) Close() { |
||
55 | c.close <- struct{}{} |
||
56 | close(c.close) |
||
57 | c.c = nil |
||
58 | } |
||
59 | |||
60 | // Set sets the value of the given key. |
||
61 | func (c *Cache) Set(key string, duration time.Duration) { |
||
62 | var expires int64 |
||
63 | if duration > 0 { |
||
64 | expires = time.Now().Add(duration).UnixNano() |
||
65 | } |
||
66 | |||
67 | c.mu.Lock() |
||
68 | defer c.mu.Unlock() |
||
69 | |||
70 | c.c[key] = expires |
||
71 | } |
||
72 | |||
73 | // Exists returns true if the given key exists. |
||
74 | func (c *Cache) Exists(key string) bool { |
||
75 | c.mu.RLock() |
||
76 | defer c.mu.RUnlock() |
||
77 | |||
78 | expires, ok := c.c[key] |
||
79 | if !ok { |
||
80 | return false |
||
81 | } |
||
82 | |||
83 | if expires > 0 && expires < time.Now().UnixNano() { |
||
84 | return false |
||
85 | } |
||
86 | |||
87 | return true |
||
88 | } |
||
89 | |||
90 | // Delete deletes the given key. |
||
91 | func (c *Cache) Delete(key string) { |
||
92 | c.mu.Lock() |
||
93 | defer c.mu.Unlock() |
||
94 | |||
95 | delete(c.c, key) |
||
96 | } |
||
97 | |||
98 | // DeleteAll deletes all keys. |
||
99 | func (c *Cache) DeleteAll() { |
||
100 | c.mu.Lock() |
||
101 | defer c.mu.Unlock() |
||
102 | |||
103 | c.c = make(map[string]int64) |
||
104 | } |
||
105 |