-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduplicate.go
More file actions
63 lines (54 loc) · 968 Bytes
/
Copy pathduplicate.go
File metadata and controls
63 lines (54 loc) · 968 Bytes
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
package golog
import (
"sync"
"time"
)
var duplicateVal *duplicate
type msgCache struct {
count int
start time.Time
}
type duplicate struct {
count int
key map[string]*msgCache
max int
locker sync.RWMutex
}
func newDuplicate(count int, dd time.Duration) *duplicate {
d := &duplicate{
max: count,
key: make(map[string]*msgCache),
locker: sync.RWMutex{},
}
go d.cleanDuplicate(dd)
return d
}
// 返回是否要写入
func (d *duplicate) addMsg(key string) bool {
d.locker.Lock()
defer d.locker.Unlock()
if _, ok := d.key[key]; !ok {
d.key[key] = &msgCache{
start: time.Now(),
count: 1,
}
return true
}
d.key[key].count += 1
if d.key[key].count >= d.max {
delete(d.key, key)
}
return false
}
func (d *duplicate) cleanDuplicate(dd time.Duration) {
for {
d.locker.Lock()
for k := range d.key {
if time.Since(d.key[k].start) > dd {
delete(d.key, k)
}
}
d.locker.Unlock()
time.Sleep(dd)
}
}