forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sheddingstat.go
73 lines (63 loc) · 1.48 KB
/
sheddingstat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package load
import (
"sync/atomic"
"time"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stat"
)
type (
// A SheddingStat is used to store the statistics for load shedding.
SheddingStat struct {
name string
total int64
pass int64
drop int64
}
snapshot struct {
Total int64
Pass int64
Drop int64
}
)
// NewSheddingStat returns a SheddingStat.
func NewSheddingStat(name string) *SheddingStat {
st := &SheddingStat{
name: name,
}
go st.run()
return st
}
// IncrementTotal increments the total requests.
func (s *SheddingStat) IncrementTotal() {
atomic.AddInt64(&s.total, 1)
}
// IncrementPass increments the passed requests.
func (s *SheddingStat) IncrementPass() {
atomic.AddInt64(&s.pass, 1)
}
// IncrementDrop increments the dropped requests.
func (s *SheddingStat) IncrementDrop() {
atomic.AddInt64(&s.drop, 1)
}
func (s *SheddingStat) reset() snapshot {
return snapshot{
Total: atomic.SwapInt64(&s.total, 0),
Pass: atomic.SwapInt64(&s.pass, 0),
Drop: atomic.SwapInt64(&s.drop, 0),
}
}
func (s *SheddingStat) run() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for range ticker.C {
c := stat.CpuUsage()
st := s.reset()
if st.Drop == 0 {
logx.Statf("(%s) shedding_stat [1m], cpu: %d, total: %d, pass: %d, drop: %d",
s.name, c, st.Total, st.Pass, st.Drop)
} else {
logx.Statf("(%s) shedding_stat_drop [1m], cpu: %d, total: %d, pass: %d, drop: %d",
s.name, c, st.Total, st.Pass, st.Drop)
}
}
}