sheddingstat.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // A SheddingStat is used to store the statistics for load shedding.
  10. SheddingStat struct {
  11. name string
  12. total int64
  13. pass int64
  14. drop int64
  15. }
  16. snapshot struct {
  17. Total int64
  18. Pass int64
  19. Drop int64
  20. }
  21. )
  22. // NewSheddingStat returns a SheddingStat.
  23. func NewSheddingStat(name string) *SheddingStat {
  24. st := &SheddingStat{
  25. name: name,
  26. }
  27. go st.run()
  28. return st
  29. }
  30. // IncrementTotal increments the total requests.
  31. func (s *SheddingStat) IncrementTotal() {
  32. atomic.AddInt64(&s.total, 1)
  33. }
  34. // IncrementPass increments the passed requests.
  35. func (s *SheddingStat) IncrementPass() {
  36. atomic.AddInt64(&s.pass, 1)
  37. }
  38. // IncrementDrop increments the dropped requests.
  39. func (s *SheddingStat) IncrementDrop() {
  40. atomic.AddInt64(&s.drop, 1)
  41. }
  42. func (s *SheddingStat) reset() snapshot {
  43. return snapshot{
  44. Total: atomic.SwapInt64(&s.total, 0),
  45. Pass: atomic.SwapInt64(&s.pass, 0),
  46. Drop: atomic.SwapInt64(&s.drop, 0),
  47. }
  48. }
  49. func (s *SheddingStat) run() {
  50. ticker := time.NewTicker(time.Minute)
  51. defer ticker.Stop()
  52. for range ticker.C {
  53. c := stat.CpuUsage()
  54. st := s.reset()
  55. if st.Drop == 0 {
  56. logx.Statf("(%s) shedding_stat [1m], cpu: %d, total: %d, pass: %d, drop: %d",
  57. s.name, c, st.Total, st.Pass, st.Drop)
  58. } else {
  59. logx.Statf("(%s) shedding_stat_drop [1m], cpu: %d, total: %d, pass: %d, drop: %d",
  60. s.name, c, st.Total, st.Pass, st.Drop)
  61. }
  62. }
  63. }