-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
57 lines (48 loc) · 940 Bytes
/
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
package mecachis
import (
e "github.com/sonirico/mecachis/engines"
lru "github.com/sonirico/mecachis/engines/lru"
"sync"
)
const (
basePath = "/mecachis/"
)
type Cache interface {
Add(k string, v MemoryView) error
Get(k string) (MemoryView, bool)
}
type cache struct {
sync.RWMutex
engine e.Engine
}
func NewCache(cap uint64, cType e.CacheType) *cache {
return &cache{
engine: newEngine(cType, cap),
}
}
func (c *cache) Add(key string, value MemoryView) error {
c.Lock()
defer c.Unlock()
res := c.engine.Insert(key, value)
if !res {
return NewDuplicatedKeyError(key)
}
return nil
}
func (c *cache) Get(key string) (MemoryView, bool) {
c.RLock()
defer c.RUnlock()
res, ok := c.engine.Access(key)
if !ok {
return nil, false
}
data := res.(MemoryView)
return data, ok
}
func newEngine(cType e.CacheType, capacity uint64) e.Engine {
switch cType {
case e.LRU:
return lru.New(capacity)
}
return nil
}