github.com/lingyao2333/mo-zero@v1.4.1/core/load/sheddingstat.go (about) 1 package load 2 3 import ( 4 "sync/atomic" 5 "time" 6 7 "github.com/lingyao2333/mo-zero/core/logx" 8 "github.com/lingyao2333/mo-zero/core/stat" 9 ) 10 11 type ( 12 // A SheddingStat is used to store the statistics for load shedding. 13 SheddingStat struct { 14 name string 15 total int64 16 pass int64 17 drop int64 18 } 19 20 snapshot struct { 21 Total int64 22 Pass int64 23 Drop int64 24 } 25 ) 26 27 // NewSheddingStat returns a SheddingStat. 28 func NewSheddingStat(name string) *SheddingStat { 29 st := &SheddingStat{ 30 name: name, 31 } 32 go st.run() 33 return st 34 } 35 36 // IncrementTotal increments the total requests. 37 func (s *SheddingStat) IncrementTotal() { 38 atomic.AddInt64(&s.total, 1) 39 } 40 41 // IncrementPass increments the passed requests. 42 func (s *SheddingStat) IncrementPass() { 43 atomic.AddInt64(&s.pass, 1) 44 } 45 46 // IncrementDrop increments the dropped requests. 47 func (s *SheddingStat) IncrementDrop() { 48 atomic.AddInt64(&s.drop, 1) 49 } 50 51 func (s *SheddingStat) loop(c <-chan time.Time) { 52 for range c { 53 st := s.reset() 54 55 if !logEnabled.True() { 56 continue 57 } 58 59 c := stat.CpuUsage() 60 if st.Drop == 0 { 61 logx.Statf("(%s) shedding_stat [1m], cpu: %d, total: %d, pass: %d, drop: %d", 62 s.name, c, st.Total, st.Pass, st.Drop) 63 } else { 64 logx.Statf("(%s) shedding_stat_drop [1m], cpu: %d, total: %d, pass: %d, drop: %d", 65 s.name, c, st.Total, st.Pass, st.Drop) 66 } 67 } 68 } 69 70 func (s *SheddingStat) reset() snapshot { 71 return snapshot{ 72 Total: atomic.SwapInt64(&s.total, 0), 73 Pass: atomic.SwapInt64(&s.pass, 0), 74 Drop: atomic.SwapInt64(&s.drop, 0), 75 } 76 } 77 78 func (s *SheddingStat) run() { 79 ticker := time.NewTicker(time.Minute) 80 defer ticker.Stop() 81 82 s.loop(ticker.C) 83 }