rate.go 897 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package limiter
  2. import (
  3. "golang.org/x/time/rate"
  4. "sync"
  5. )
  6. var _ RateLimiter = (*rateLimiter)(nil)
  7. type RateLimiter interface {
  8. addKey(key string) *rate.Limiter
  9. getLimiter(key string) *rate.Limiter
  10. Allow(key string) bool
  11. }
  12. type rateLimiter struct {
  13. list *sync.Map
  14. limit rate.Limit
  15. burst int
  16. }
  17. func NewRateLimiter(limit int, burst int) RateLimiter {
  18. return &rateLimiter{
  19. list: new(sync.Map),
  20. limit: rate.Limit(limit),
  21. burst: burst,
  22. }
  23. }
  24. func (i *rateLimiter) addKey(key string) *rate.Limiter {
  25. store, _ := i.list.LoadOrStore(key, rate.NewLimiter(i.limit, i.burst))
  26. return store.(*rate.Limiter)
  27. }
  28. func (i *rateLimiter) getLimiter(key string) *rate.Limiter {
  29. limiter, exists := i.list.Load(key)
  30. if !exists {
  31. return i.addKey(key)
  32. }
  33. return limiter.(*rate.Limiter)
  34. }
  35. func (i *rateLimiter) Allow(key string) bool {
  36. limiter := i.getLimiter(key)
  37. return limiter.Allow()
  38. }