-
Notifications
You must be signed in to change notification settings - Fork 11
/
limiter.go
58 lines (47 loc) · 1.14 KB
/
limiter.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
package clickhouse
import (
"fmt"
composer "github.com/leprosus/golang-composer"
"sync"
"sync/atomic"
)
type Limiter struct {
once sync.Once
maxRequests uint32
requestsCounter int32
queue chan int32
}
// MaxRequests sets requests limitation (zero is limitation off)
func (lim *Limiter) MaxRequests(limit int) {
atomic.StoreUint32(&lim.maxRequests, uint32(limit))
message := fmt.Sprintf("Set max request pool = %d", limit)
cfg.logger.debug(message)
}
func (lim *Limiter) initQueue() {
lim.queue = make(chan int32)
go func() {
for step := range lim.queue {
atomic.AddInt32(&lim.requestsCounter, step)
if atomic.LoadUint32(&lim.maxRequests) > 0 {
if atomic.LoadUint32(&lim.maxRequests) <= uint32(atomic.LoadInt32(&lim.requestsCounter)) {
composer.GetComposer().Pause()
} else {
composer.GetComposer().Play()
}
} else {
composer.GetComposer().Play()
}
}
}()
}
func (lim *Limiter) increase() {
lim.once.Do(lim.initQueue)
lim.queue <- 1
}
func (lim *Limiter) reduce() {
lim.once.Do(lim.initQueue)
lim.queue <- -1
}
func (lim *Limiter) waitForRest() {
composer.GetComposer().NeedWait()
}