-
Notifications
You must be signed in to change notification settings - Fork 54
/
item.go
102 lines (88 loc) · 1.93 KB
/
item.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
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
97
98
99
100
101
102
package zcache
import (
"sync"
"time"
)
// Item Item
type Item struct {
sync.RWMutex
key string
data interface{}
lifeSpan time.Duration
createdTime time.Time
accessedTime time.Time
accessCount int64
intervalLifeSpan bool
deleteCallback func(key string) bool
}
// NewCacheItem NewCacheItem
func NewCacheItem(key string, data interface{}, lifeSpan time.Duration) *Item {
t := time.Now()
return &Item{
key: key,
lifeSpan: lifeSpan,
createdTime: t,
accessedTime: t,
accessCount: 0,
intervalLifeSpan: false,
deleteCallback: nil,
data: data,
}
}
func (item *Item) keepAlive() {
item.Lock()
item.accessedTime = time.Now()
item.accessCount++
item.Unlock()
}
// LifeSpan LifeSpan
func (item *Item) LifeSpan() time.Duration {
return item.lifeSpan
}
// LifeSpan LifeSpan
func (item *Item) IntervalLifeSpan() bool {
return item.intervalLifeSpan
}
// LifeSpanUint LifeSpanUint
func (item *Item) LifeSpanUint() uint {
return uint(item.lifeSpan / time.Second)
}
// AccessedTime AccessedTime
func (item *Item) AccessedTime() time.Time {
item.RLock()
defer item.RUnlock()
return item.accessedTime
}
// CreatedTime CreatedTime
func (item *Item) CreatedTime() time.Time {
return item.createdTime
}
// RemainingLife RemainingLife
func (item *Item) RemainingLife() time.Duration {
if item.lifeSpan == 0 {
return -1
}
return time.Until(item.createdTime.Add(item.lifeSpan))
}
// AccessCount AccessCount
func (item *Item) AccessCount() int64 {
item.RLock()
defer item.RUnlock()
return item.accessCount
}
// Key item key
func (item *Item) Key() interface{} {
return item.key
}
// Data data
func (item *Item) Data() interface{} {
item.RLock()
defer item.RUnlock()
return item.data
}
// SetDeleteCallback SetDeleteCallback
func (item *Item) SetDeleteCallback(fn func(key string) bool) {
item.Lock()
item.deleteCallback = fn
item.Unlock()
}