-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d55f585
commit af4dd92
Showing
4 changed files
with
86 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package utils | ||
|
||
import "time" | ||
|
||
var LimitQueue map[string][]int64 | ||
var ok bool | ||
|
||
//单机时间滑动窗口限流法 | ||
func LimitFreqSingle(queueName string, count uint, timeWindow int64) bool { | ||
currTime := time.Now().Unix() | ||
if LimitQueue == nil { | ||
LimitQueue = make(map[string][]int64) | ||
} | ||
if _, ok = LimitQueue[queueName]; !ok { | ||
LimitQueue[queueName] = make([]int64, 0) | ||
} | ||
//队列未满 | ||
if uint(len(LimitQueue[queueName])) < count { | ||
LimitQueue[queueName] = append(LimitQueue[queueName], currTime) | ||
return true | ||
} | ||
//队列满了,取出最早访问的时间 | ||
earlyTime := LimitQueue[queueName][0] | ||
//说明最早期的时间还在时间窗口内,还没过期,所以不允许通过 | ||
if currTime-earlyTime <= timeWindow { | ||
return false | ||
} else { | ||
//说明最早期的访问应该过期了,去掉最早期的 | ||
LimitQueue[queueName] = LimitQueue[queueName][1:] | ||
LimitQueue[queueName] = append(LimitQueue[queueName], currTime) | ||
} | ||
return true | ||
} |