buckets.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package rate
  2. import (
  3. "sync"
  4. "time"
  5. ctime "github.com/cherry-game/cherry/extend/time"
  6. clog "github.com/cherry-game/cherry/logger"
  7. )
  8. type Buckets struct {
  9. bucketMap map[string]*Bucket // key:name, value:*Bucket
  10. lock *sync.RWMutex // lock
  11. }
  12. func NewBuckets() *Buckets {
  13. return &Buckets{
  14. bucketMap: map[string]*Bucket{},
  15. lock: &sync.RWMutex{},
  16. }
  17. }
  18. func (p *Buckets) Add(name string, interval time.Duration, capacity, quantum int64) (*Bucket, bool) {
  19. if name == "" {
  20. return nil, false
  21. }
  22. p.lock.Lock()
  23. defer p.lock.Unlock()
  24. bucket, found := p.bucketMap[name]
  25. if found {
  26. return bucket, found
  27. }
  28. bucket = NewBucketWithQuantum(
  29. interval*time.Second,
  30. capacity,
  31. quantum,
  32. )
  33. p.bucketMap[name] = bucket
  34. return bucket, true
  35. }
  36. func (p *Buckets) Get(name string) (*Bucket, bool) {
  37. p.lock.RLock()
  38. defer p.lock.RUnlock()
  39. bucket, found := p.bucketMap[name]
  40. return bucket, found
  41. }
  42. func (p *Buckets) Remove(name string) {
  43. p.lock.Lock()
  44. defer p.lock.Unlock()
  45. delete(p.bucketMap, name)
  46. }
  47. func (p *Buckets) Clean(beforeMinute int64) {
  48. p.lock.Lock()
  49. defer p.lock.Unlock()
  50. for name, bucket := range p.bucketMap {
  51. now := ctime.NewTime(time.Now(), false)
  52. lastTime := ctime.NewTime(bucket.lastTime, false)
  53. minute := lastTime.DiffInMinutes(&now)
  54. if minute >= beforeMinute {
  55. delete(p.bucketMap, name)
  56. clog.Infof("clean bucket. [name = %s]", name)
  57. }
  58. }
  59. }