-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.go
More file actions
52 lines (44 loc) · 1.01 KB
/
cache.go
File metadata and controls
52 lines (44 loc) · 1.01 KB
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
package gocache
import (
"sync"
"github.com/devhg/gocache/lru"
)
// cache 并发缓存,对核心lru进行封装
type cache struct {
sync.RWMutex
lru *lru.Cache
cacheBytes int64
nhit, nget int64
nevict int64 // number of evictions
}
// add 添加缓存
func (c *cache) add(key string, val ByteView) {
c.Lock()
defer c.Unlock()
// 延迟初始化(Lazy Initialization),一个对象的延迟初始化意味
// 着该对象的创建将会延迟至第一次使用该对象时。主要用于提高性能,并减少程序内存要求。
if c.lru == nil {
c.lru = lru.New(&lru.CacheConfig{
MaxBytes: c.cacheBytes,
OnEvicted: func(s string, value lru.Value) {
c.nevict++
},
})
}
c.lru.Add(key, val)
c.cacheBytes += int64(val.Len())
}
// 获取缓存
func (c *cache) get(key string) (val ByteView, ok bool) {
c.RLock()
defer c.RUnlock()
if c.lru == nil {
return
}
c.nget++
if v, hit := c.lru.Get(key); hit {
c.nhit++ // 命中返回true
return v.(ByteView), hit
}
return
}