Skip to content

Instantly share code, notes, and snippets.

@wrfly
Created June 5, 2021 15:46
Show Gist options
  • Save wrfly/64d8881b90e1a5ff9e658db15530ba35 to your computer and use it in GitHub Desktop.
Save wrfly/64d8881b90e1a5ff9e658db15530ba35 to your computer and use it in GitHub Desktop.
golang dynamic rate limiter
package main
import (
"fmt"
"sync"
"time"
"go.uber.org/ratelimit"
)
type limiter struct {
l ratelimit.Limiter
m sync.RWMutex
qps int
}
func (l *limiter) ReSet(qps int) {
l.m.Lock()
l.qps = qps
l.l = ratelimit.New(qps, ratelimit.WithoutSlack)
l.m.Unlock()
}
func (l *limiter) Take() time.Time {
l.m.RLock()
now := l.l.Take()
l.m.RUnlock()
return now
}
func main() {
rl := &limiter{}
rl.ReSet(10)
prev := time.Now()
for i := 0; i < 10; i++ {
now := rl.Take()
if i > 0 {
fmt.Println(i, now.Sub(prev))
}
prev = now
if i == 3 {
rl.ReSet(5)
}
if i == 7 {
rl.ReSet(3)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment