-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate.go
82 lines (73 loc) · 1.34 KB
/
rate.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
package rate
import (
"sync/atomic"
"time"
)
// Rate control speed for QPS
type Rate struct {
tokenBucket chan struct{}
stop chan struct{}
restart chan struct{}
limit int
qps int64
}
// NewRate Initialization entry
func NewRate(limit int) *Rate {
return &Rate{
tokenBucket: make(chan struct{}, 1),
stop: make(chan struct{}),
restart: make(chan struct{}),
limit: limit,
}
}
// Run new token to bucket
func (r *Rate) Run() {
tick := time.NewTicker(time.Second / time.Duration(r.limit))
for {
select {
case <-tick.C:
r.tokenBucket <- struct{}{}
case <-r.stop:
r.restart <- struct{}{}
return
}
}
}
// Stop stop new token to bucket
func (r *Rate) Stop() {
r.stop <- struct{}{}
}
// Restart for new limit
func (r *Rate) Restart(limit int) {
r.limit = limit
r.Stop()
<-r.restart
go r.Run()
}
// GetToken control QPS
func (r *Rate) GetToken() bool {
timer := time.NewTimer(time.Second / time.Duration(r.limit))
select {
case <-r.tokenBucket:
r.qps = atomic.AddInt64(&r.qps, 1)
return true
case <-timer.C:
return false
}
}
// QPS get rate QPS
func (r *Rate) QPS() <-chan int64 {
tick := time.NewTicker(1 * time.Second)
qps := make(chan int64)
var zero int64
go func() {
for {
select {
case <-tick.C:
qps <- r.qps
r.qps = zero
}
}
}()
return qps
}