-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_bucket.go
84 lines (64 loc) · 1.16 KB
/
token_bucket.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
83
84
package limiter
import (
"sync"
"time"
)
type TbConfig struct {
QPS int64
MaxCap int64
}
type TokenBucket struct {
*TbConfig
m sync.Mutex
available int64
lastTime time.Time
}
var _ Limiter = &TokenBucket{}
func NewTokenBucket(c *TbConfig) Limiter {
return &TokenBucket{
TbConfig: c,
m: sync.Mutex{},
available: c.QPS,
lastTime: time.Now(),
}
}
func (tb *TokenBucket) Take() error {
tb.m.Lock()
defer tb.m.Unlock()
tb.fill()
if 1 <= tb.available {
tb.available -= 1
return nil
}
return ErrNoTEnoughToken
}
func (tb *TokenBucket) Put(cnt int64) error {
tb.m.Lock()
defer tb.m.Unlock()
tb.fill()
tb.available += cnt
if tb.MaxCap > 0 && tb.available > tb.MaxCap {
tb.available = tb.MaxCap
}
return nil
}
func (tb *TokenBucket) Cnt() int64 {
tb.m.Lock()
defer tb.m.Unlock()
tb.fill()
return tb.available
}
func (tb *TokenBucket) fill() error {
n := time.Now()
timeUnit := n.Sub(tb.lastTime).Seconds()
fillCnt := int64(timeUnit) * tb.QPS
if fillCnt <= 0 {
return nil
}
tb.available += fillCnt
if tb.MaxCap > 0 && tb.available > tb.MaxCap {
tb.available = tb.MaxCap
}
tb.lastTime = n
return nil
}