Created
September 24, 2024 11:16
-
-
Save hxzhouh/bbfc5b75047d008c3c58893594801230 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 TokenBucket struct { | |
| mu sync.Mutex | |
| bucketSize int | |
| capacity chan struct{} | |
| interval time.Duration | |
| refillRate int | |
| } | |
| func NewTokenBucket(capacity int, refillRate int, interval time.Duration) *TokenBucket { | |
| tl := &TokenBucket{ | |
| capacity: make(chan struct{}, capacity), | |
| bucketSize: capacity, | |
| interval: interval, | |
| refillRate: refillRate, | |
| } | |
| go tl.refill() | |
| return tl | |
| } | |
| // Allow 方法用于判断当前请求是否被允许。 | |
| func (t *TokenBucket) Allow() bool { | |
| select { | |
| case <-t.capacity: | |
| return true | |
| default: | |
| return false | |
| } | |
| } | |
| func (t *TokenBucket) refill() { | |
| ticker := time.NewTicker(t.interval) | |
| for { | |
| select { | |
| case <-ticker.C: | |
| for i := 0; i < t.refillRate; i++ { | |
| // If the channel is full, It is not a rigorous realization. | |
| if len(t.capacity) >= cap(t.capacity) { | |
| continue | |
| } | |
| t.capacity <- struct{}{} | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment