/
throttle.go
64 lines (52 loc) · 1.11 KB
/
throttle.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
/*
* Radon
*
* Copyright 2018 The Radon Authors.
* Code is licensed under the GPLv3.
*
*/
package xbase
import (
"sync"
"time"
"xbase/sync2"
"github.com/beefsack/go-rate"
)
// Throttle tuple.
type Throttle struct {
limit sync2.AtomicInt32
rate *rate.RateLimiter
mu sync.Mutex
}
// NewThrottle creates the new throttle.
func NewThrottle(l int) *Throttle {
return &Throttle{
limit: sync2.NewAtomicInt32(int32(l)),
rate: rate.New(l, time.Second),
}
}
// Acquire used to acquire the lock of throttle.
func (throttle *Throttle) Acquire() {
if throttle.limit.Get() <= 0 {
return
}
throttle.mu.Lock()
defer throttle.mu.Unlock()
throttle.rate.Wait()
}
// Release used to do nothing.
func (throttle *Throttle) Release() {
}
// Set used to set the quota for the throttle.
func (throttle *Throttle) Set(l int) {
throttle.mu.Lock()
defer throttle.mu.Unlock()
throttle.limit.Set(int32(l))
throttle.rate = rate.New(l, time.Second)
}
// Limits returns the limits of the throttle.
func (throttle *Throttle) Limits() int {
throttle.mu.Lock()
defer throttle.mu.Unlock()
return int(throttle.limit.Get())
}