forked from Teddy-Schmitz/ali_mns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qps_monitor.go
55 lines (47 loc) · 1.09 KB
/
qps_monitor.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
package ali_mns
import (
"sync/atomic"
"time"
)
type QPSMonitor struct {
qpsLimit int32
latestIndex int32
delaySecond int32
totalQueries []int32
}
func (p *QPSMonitor) Pulse() {
index := int32(time.Now().Second()) % atomic.LoadInt32(&p.delaySecond)
if atomic.LoadInt32(&p.latestIndex) != index {
atomic.StoreInt32(&p.latestIndex, index)
atomic.StoreInt32(&p.totalQueries[p.latestIndex], 0)
}
atomic.AddInt32(&p.totalQueries[index], 1)
}
func (p *QPSMonitor) QPS() int32 {
var totalCount int32 = 0
for i, _ := range p.totalQueries {
if int32(i) != atomic.LoadInt32(&p.latestIndex) {
totalCount += atomic.LoadInt32(&p.totalQueries[i])
}
}
return totalCount / (p.delaySecond - 1)
}
func (p *QPSMonitor) checkQPS() {
p.Pulse()
if p.qpsLimit > 0 {
for p.QPS() > p.qpsLimit {
time.Sleep(time.Millisecond * 10)
}
}
}
func NewQPSMonitor(delaySecond int32, qpsLimit int32) *QPSMonitor {
if delaySecond < 5 {
delaySecond = 5
}
monitor := QPSMonitor{
qpsLimit: qpsLimit,
delaySecond: delaySecond,
totalQueries: make([]int32, delaySecond),
}
return &monitor
}