-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqps.go
45 lines (40 loc) · 784 Bytes
/
qps.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
package mns
import (
"log"
"sync/atomic"
"time"
)
// QPS 限速
type QPS struct {
qpsLimit int64
currentIndex int64
perSecondQuery int64
}
// NewQPS NewQPS
func NewQPS(qpsLimit int64) *QPS {
qps := QPS{
qpsLimit: qpsLimit,
perSecondQuery: 0,
}
return &qps
}
// Pulse Pulse
func (qps *QPS) pulse() {
index := time.Now().Unix() % 5
if index != qps.currentIndex {
atomic.StoreInt64(&qps.currentIndex, index)
atomic.StoreInt64(&qps.perSecondQuery, 0)
}
atomic.AddInt64(&qps.perSecondQuery, 1)
}
// CheckQPS CheckQPS
func (qps *QPS) CheckQPS() {
qps.pulse()
if qps.qpsLimit > 0 {
for qps.perSecondQuery > qps.qpsLimit {
qps.pulse()
log.Printf("wait 10 millisecond,qps:%d", qps.perSecondQuery)
time.Sleep(time.Millisecond * 10)
}
}
}