-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixation1.go
More file actions
50 lines (44 loc) · 957 Bytes
/
fixation1.go
File metadata and controls
50 lines (44 loc) · 957 Bytes
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
package util
import (
"sync/atomic"
"time"
)
/**
固定窗口计数器-基于给定时间范围
精确度最差
*/
type CounterFix struct {
count int64 // 当前次数
maxNum int64 // 次数限制
durTime time.Duration // 间隔时间
endTime time.Time //限制结束时间
}
// 设置计数器
// num / td 限制当前时间范围的次数 eg 1/time.Second 每秒1次
func (c *CounterFix) Set(num int64, td time.Duration) {
c.maxNum = num
c.durTime = td
c.setEndTime()
}
// 重置结束时间
func (c *CounterFix) setEndTime() {
c.endTime = time.Now().Add(c.durTime)
}
// 判断是否满足限流器要求
func (c *CounterFix) Allow() bool {
now := time.Now()
// 在规定时间内 判断请求次数
if now.Before(c.endTime) {
atomic.AddInt64(&c.count, 1)
if c.count > c.maxNum {
// 重置计数器
return false
} else {
return true
}
} else {
c.count = 1
c.setEndTime()
return true
}
}