-
Notifications
You must be signed in to change notification settings - Fork 0
/
fixed_window_limiter.go
51 lines (44 loc) · 1.14 KB
/
fixed_window_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
package ratelimiter
import (
"sync"
"time"
)
type FixedWindowLimiter struct {
windowDuration time.Duration // 一个窗口的时长大小
maxRequestCount int // 一个窗口允许多少请求
windowId int // 当前窗口的id
requestCount int // 当前窗口已有的请求个数
mu *sync.Mutex
}
func (l *FixedWindowLimiter) Allow() bool {
id := int(time.Now().UnixNano() / int64(l.windowDuration))
l.mu.Lock()
defer l.mu.Unlock()
if id > l.windowId {
l.windowId = id
l.requestCount = 0
}
if l.requestCount < l.maxRequestCount {
l.requestCount += 1
return true
}
return false
}
func NewFixedWindowLimiter(windowDuration time.Duration, maxRequestCount int) *FixedWindowLimiter {
return &FixedWindowLimiter{
windowDuration: windowDuration,
maxRequestCount: maxRequestCount,
mu: &sync.Mutex{},
windowId: 0,
requestCount: 0,
}
}
func NewDefaultFixedWindowLimiter() *FixedWindowLimiter {
return &FixedWindowLimiter{
windowDuration: time.Second,
maxRequestCount: 100,
mu: &sync.Mutex{},
windowId: 0,
requestCount: 0,
}
}