cachestat.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package cache
  2. import (
  3. "sync/atomic"
  4. "time"
  5. "git.i2edu.net/i2/go-zero/core/logx"
  6. )
  7. const statInterval = time.Minute
  8. // A Stat is used to stat the cache.
  9. type Stat struct {
  10. name string
  11. // export the fields to let the unit tests working,
  12. // reside in internal package, doesn't matter.
  13. Total uint64
  14. Hit uint64
  15. Miss uint64
  16. DbFails uint64
  17. }
  18. // NewStat returns a Stat.
  19. func NewStat(name string) *Stat {
  20. ret := &Stat{
  21. name: name,
  22. }
  23. go ret.statLoop()
  24. return ret
  25. }
  26. // IncrementTotal increments the total count.
  27. func (s *Stat) IncrementTotal() {
  28. atomic.AddUint64(&s.Total, 1)
  29. }
  30. // IncrementHit increments the hit count.
  31. func (s *Stat) IncrementHit() {
  32. atomic.AddUint64(&s.Hit, 1)
  33. }
  34. // IncrementMiss increments the miss count.
  35. func (s *Stat) IncrementMiss() {
  36. atomic.AddUint64(&s.Miss, 1)
  37. }
  38. // IncrementDbFails increments the db fail count.
  39. func (s *Stat) IncrementDbFails() {
  40. atomic.AddUint64(&s.DbFails, 1)
  41. }
  42. func (s *Stat) statLoop() {
  43. ticker := time.NewTicker(statInterval)
  44. defer ticker.Stop()
  45. for range ticker.C {
  46. total := atomic.SwapUint64(&s.Total, 0)
  47. if total == 0 {
  48. continue
  49. }
  50. hit := atomic.SwapUint64(&s.Hit, 0)
  51. percent := 100 * float32(hit) / float32(total)
  52. miss := atomic.SwapUint64(&s.Miss, 0)
  53. dbf := atomic.SwapUint64(&s.DbFails, 0)
  54. logx.Statf("dbcache(%s) - qpm: %d, hit_ratio: %.1f%%, hit: %d, miss: %d, db_fails: %d",
  55. s.name, total, percent, hit, miss, dbf)
  56. }
  57. }