Created
September 24, 2024 11:01
-
-
Save hxzhouh/51020e18622c2e38ebf21cd6a9dc5cc6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
type FixedWindowCounter struct { | |
mu sync.Mutex | |
count int | |
limit int | |
duration time.Duration | |
} | |
func NewFixedWindowCounter(limit int, duration time.Duration) *FixedWindowCounter { | |
l := &FixedWindowCounter{ | |
limit: limit, | |
duration: duration, // Setting the duration of the time window。 | |
} | |
go l.resetLimit() | |
return l | |
} | |
func (f *FixedWindowCounter) resetLimit() { | |
ticker := time.NewTicker(f.duration) | |
for { | |
select { | |
case <-ticker.C: | |
f.mu.Lock() | |
f.count = 0 | |
f.mu.Unlock() | |
} | |
} | |
} | |
func (f *FixedWindowCounter) Allow() bool { | |
f.mu.Lock() | |
defer f.mu.Unlock() | |
// allowed request | |
if f.count < f.limit { | |
f.count++ | |
return true | |
} | |
// reject request | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment