sheddingstat.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package load
  2. import (
  3. "sync/atomic"
  4. "time"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "github.com/tal-tech/go-zero/core/stat"
  7. )
  8. type (
  9. SheddingStat struct {
  10. name string
  11. total int64
  12. pass int64
  13. drop int64
  14. }
  15. snapshot struct {
  16. Total int64
  17. Pass int64
  18. Drop int64
  19. }
  20. )
  21. func NewSheddingStat(name string) *SheddingStat {
  22. st := &SheddingStat{
  23. name: name,
  24. }
  25. go st.run()
  26. return st
  27. }
  28. func (s *SheddingStat) IncrementTotal() {
  29. atomic.AddInt64(&s.total, 1)
  30. }
  31. func (s *SheddingStat) IncrementPass() {
  32. atomic.AddInt64(&s.pass, 1)
  33. }
  34. func (s *SheddingStat) IncrementDrop() {
  35. atomic.AddInt64(&s.drop, 1)
  36. }
  37. func (s *SheddingStat) reset() snapshot {
  38. return snapshot{
  39. Total: atomic.SwapInt64(&s.total, 0),
  40. Pass: atomic.SwapInt64(&s.pass, 0),
  41. Drop: atomic.SwapInt64(&s.drop, 0),
  42. }
  43. }
  44. func (s *SheddingStat) run() {
  45. ticker := time.NewTicker(time.Minute)
  46. defer ticker.Stop()
  47. for range ticker.C {
  48. c := stat.CpuUsage()
  49. st := s.reset()
  50. if st.Drop == 0 {
  51. logx.Statf("(%s) shedding_stat [1m], cpu: %d, total: %d, pass: %d, drop: %d",
  52. s.name, c, st.Total, st.Pass, st.Drop)
  53. } else {
  54. logx.Statf("(%s) shedding_stat_drop [1m], cpu: %d, total: %d, pass: %d, drop: %d",
  55. s.name, c, st.Total, st.Pass, st.Drop)
  56. }
  57. }
  58. }