-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_safe.go
48 lines (39 loc) · 874 Bytes
/
cache_safe.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
package xcache
import (
"sync"
"xcache/cache"
"xcache/cache/fifo"
"xcache/cache/lfu"
"xcache/cache/lru"
)
type Cache struct {
mu sync.RWMutex
cache cache.Cache
}
func NewCache(cacheType cache.CacheType, maxBytes int, onEvicted func(string, cache.Value)) (c *Cache) {
c = new(Cache)
switch cacheType {
case cache.LRUCACHE:
c.cache = lru.NewLRU(maxBytes, onEvicted)
case cache.LFUCACHE:
c.cache = lfu.NewLFU(maxBytes, onEvicted)
case cache.FIFOCACHE:
c.cache = fifo.NewFIFO(maxBytes, onEvicted)
default:
c.cache = lru.NewLRU(maxBytes, onEvicted)
}
return
}
func (c *Cache) set(key string, value ByteView) {
c.mu.Lock()
defer c.mu.Unlock()
c.cache.Set(key, value)
}
func (c *Cache) get(key string) (value ByteView, ok bool) {
c.mu.RLock()
defer c.mu.RUnlock()
if v, ok := c.cache.Get(key); ok {
return v.(ByteView), true
}
return
}