cachestat.go 1.2 KB

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