forked from ccfos/nightingale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrop_ident.go
100 lines (89 loc) · 1.64 KB
/
drop_ident.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
package memsto
import (
"sync"
"time"
)
type Item struct {
Count int
Ts int64
}
type IdentCountCacheType struct {
sync.RWMutex
idents map[string]Item
}
func NewIdentCountCache() *IdentCountCacheType {
d := &IdentCountCacheType{
idents: make(map[string]Item),
}
go d.CronDeleteExpired()
return d
}
// Set ident
func (c *IdentCountCacheType) Set(ident string, count int, ts int64) {
c.Lock()
item := Item{
Count: count,
Ts: ts,
}
c.idents[ident] = item
c.Unlock()
}
func (c *IdentCountCacheType) Increment(ident string, num int) {
now := time.Now().Unix()
c.Lock()
if item, exists := c.idents[ident]; exists {
item.Count += num
item.Ts = now
c.idents[ident] = item
} else {
item := Item{
Count: num,
Ts: now,
}
c.idents[ident] = item
}
c.Unlock()
}
// check exists ident
func (c *IdentCountCacheType) Exists(ident string) bool {
c.RLock()
_, exists := c.idents[ident]
c.RUnlock()
return exists
}
func (c *IdentCountCacheType) Get(ident string) int {
c.RLock()
defer c.RUnlock()
item, exists := c.idents[ident]
if !exists {
return 0
}
return item.Count
}
func (c *IdentCountCacheType) GetsAndFlush() map[string]Item {
c.Lock()
data := make(map[string]Item)
for k, v := range c.idents {
data[k] = v
}
c.idents = make(map[string]Item)
c.Unlock()
return data
}
func (c *IdentCountCacheType) CronDeleteExpired() {
for {
time.Sleep(60 * time.Second)
c.deleteExpired()
}
}
// cron delete expired ident
func (c *IdentCountCacheType) deleteExpired() {
c.Lock()
now := time.Now().Unix()
for ident, item := range c.idents {
if item.Ts < now-120 {
delete(c.idents, ident)
}
}
c.Unlock()
}