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