counter.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package exhook
  2. import (
  3. "math"
  4. "sync"
  5. "time"
  6. )
  7. type Counter struct {
  8. count int64
  9. start int64
  10. duration int64
  11. maxCount int64
  12. lock sync.Mutex
  13. }
  14. func NewCounter(duration int64, maxCount int64) *Counter {
  15. counter := &Counter{}
  16. counter.count = 0
  17. counter.start = time.Now().UnixNano() / 1e6 // 当前毫秒时间戳
  18. if duration == 0 {
  19. counter.duration = math.MaxInt64 // duration传0表示没有时间间隔限制,计数器不刷新
  20. } else {
  21. counter.duration = duration
  22. }
  23. counter.maxCount = maxCount
  24. return counter
  25. }
  26. // Count 计数器计数
  27. // n: 计数值
  28. // refersh: 计数器是否刷新
  29. // limit: 是否达到计数最大值
  30. // num: 计数后计数器的值
  31. func (counter *Counter) Count(n int64) (refresh bool, limit bool, num int64) {
  32. now := time.Now().UnixNano() / 1e6
  33. counter.lock.Lock()
  34. defer counter.lock.Unlock()
  35. if now-counter.start < counter.duration {
  36. counter.count += n
  37. num = counter.count
  38. limit = num > counter.maxCount
  39. } else {
  40. // num = counter.count // 刷新前的最大计数
  41. counter.start = now
  42. counter.count = 0
  43. refresh = true
  44. }
  45. return
  46. }
  47. func (counter *Counter) GetCount() (num int64) {
  48. counter.lock.Lock()
  49. defer counter.lock.Unlock()
  50. return counter.count
  51. }