-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheitem.go
More file actions
96 lines (84 loc) · 1.9 KB
/
cacheitem.go
File metadata and controls
96 lines (84 loc) · 1.9 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package cache2
import (
"sync"
"time"
)
type CacheItem struct {
sync.RWMutex
key interface{}
data interface{}
// 存活时间
lifeSpan time.Duration
createOn time.Time
//最后一次访问时间
accessOn time.Time
//访问次数
accessCount int64
//从缓存中删除项目的回调方法
aboutToExpire []func(interface{})
}
// 创建新的item
func NewCacheItem(key, data interface{}, lifeSpan time.Duration) *CacheItem {
t := time.Now()
return &CacheItem{
RWMutex: sync.RWMutex{},
key: key,
data: data,
lifeSpan: lifeSpan,
createOn: t,
accessOn: t,
accessCount: 0,
aboutToExpire: nil,
}
}
// 更新最后一次访问
func (item *CacheItem) KeepAlive() {
item.RLock()
defer item.RUnlock()
item.accessOn = time.Now()
item.accessCount++
}
// 从缓存中删除项目的回调函数
func (item *CacheItem) SetAboutToExpireCallback(f func(interface{})) {
if len(item.aboutToExpire) > 0 {
item.RemoveAboutToExpireCallback()
}
item.RLock()
defer item.RUnlock()
item.aboutToExpire = append(item.aboutToExpire, f)
}
// 新增回调信息
func (item *CacheItem) AddAboutToExpireCallback(f func(interface{})) {
item.RLock()
defer item.RUnlock()
item.aboutToExpire = append(item.aboutToExpire, f)
}
// 清空回调信息
func (item *CacheItem) RemoveAboutToExpireCallback() {
item.RLock()
defer item.RUnlock()
item.aboutToExpire = nil
}
// 返回项目的过期时间
func (item *CacheItem) LifeSpan() time.Duration {
return item.lifeSpan
}
func (item *CacheItem) AccessOn() time.Time {
item.RLock()
defer item.RUnlock()
return item.accessOn
}
func (item *CacheItem) CreateOn() time.Time {
return item.createOn
}
func (item *CacheItem) AccessCount() int64 {
item.RLock()
defer item.RUnlock()
return item.accessCount
}
func (item *CacheItem) Key() interface{} {
return item.key
}
func (item *CacheItem) Data() interface{} {
return item.data
}