-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathcache.go
67 lines (55 loc) · 996 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
58
59
60
61
62
63
64
65
66
67
package cache
import (
"sync"
)
// Cache 缓存接口
type Cache interface {
Set(key string, value interface{})
Get(key string) interface{}
Del(key string)
DelOldest()
Len() int
}
// DefaultMaxBytes 默认允许占用的最大内存
const DefaultMaxBytes = 1 << 29
// safeCache 并发安全缓存
type safeCache struct {
m sync.RWMutex
cache Cache
nget, nhit int
}
func newSafeCache(cache Cache) *safeCache {
return &safeCache{
cache: cache,
}
}
func (sc *safeCache) set(key string, value interface{}) {
sc.m.Lock()
defer sc.m.Unlock()
sc.cache.Set(key, value)
}
func (sc *safeCache) get(key string) interface{} {
sc.m.RLock()
defer sc.m.RUnlock()
sc.nget++
if sc.cache == nil {
return nil
}
v := sc.cache.Get(key)
if v != nil {
// log.Println("[TourCache] hit")
sc.nhit++
}
return v
}
func (sc *safeCache) stat() *Stat {
sc.m.RLock()
defer sc.m.RUnlock()
return &Stat{
NHit: sc.nhit,
NGet: sc.nget,
}
}
type Stat struct {
NHit, NGet int
}