You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/stores/cache/cachestat.go

71 lines
1.4 KiB
Go

package cache
4 years ago
import (
"sync/atomic"
"time"
"github.com/tal-tech/go-zero/core/logx"
4 years ago
)
const statInterval = time.Minute
// A Stat is used to stat the cache.
type Stat struct {
4 years ago
name string
// export the fields to let the unit tests working,
// reside in internal package, doesn't matter.
Total uint64
Hit uint64
Miss uint64
DbFails uint64
}
// NewStat returns a Stat.
func NewStat(name string) *Stat {
ret := &Stat{
4 years ago
name: name,
}
go ret.statLoop()
return ret
}
// IncrementTotal increments the total count.
func (s *Stat) IncrementTotal() {
atomic.AddUint64(&s.Total, 1)
4 years ago
}
// IncrementHit increments the hit count.
func (s *Stat) IncrementHit() {
atomic.AddUint64(&s.Hit, 1)
4 years ago
}
// IncrementMiss increments the miss count.
func (s *Stat) IncrementMiss() {
atomic.AddUint64(&s.Miss, 1)
4 years ago
}
// IncrementDbFails increments the db fail count.
func (s *Stat) IncrementDbFails() {
atomic.AddUint64(&s.DbFails, 1)
4 years ago
}
func (s *Stat) statLoop() {
4 years ago
ticker := time.NewTicker(statInterval)
defer ticker.Stop()
for range ticker.C {
total := atomic.SwapUint64(&s.Total, 0)
if total == 0 {
continue
4 years ago
}
hit := atomic.SwapUint64(&s.Hit, 0)
percent := 100 * float32(hit) / float32(total)
miss := atomic.SwapUint64(&s.Miss, 0)
dbf := atomic.SwapUint64(&s.DbFails, 0)
logx.Statf("dbcache(%s) - qpm: %d, hit_ratio: %.1f%%, hit: %d, miss: %d, db_fails: %d",
s.name, total, percent, hit, miss, dbf)
4 years ago
}
}