-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.go
73 lines (59 loc) · 1.52 KB
/
counter.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 promgo
import (
"context"
"strconv"
"github.com/go-redis/redis/v8"
)
// Counter 计数器
type Counter interface {
Collector
Inc(context.Context, ConstLabels)
IncBy(context.Context, float64, ConstLabels)
}
// CounterOptions ...
type CounterOptions CollectorOptions
// redisCounter ...
type redisCounter struct {
redisCollector
}
// Incr 自增量,步长为1
func (rc redisCounter) Inc(ctx context.Context, constLables ConstLabels) {
rc.IncBy(ctx, 1, constLables)
}
// IncrBy 指定增量的增长; 增量 v 必须是一个非负数; 这里没有做校验。。。
func (rc redisCounter) IncBy(ctx context.Context, v float64, constLabels ConstLabels) {
rc.Rdb.HIncrByFloat(ctx, rc.key(), rc.field(constLabels), v)
}
// Collect 采集数据
func (rc redisCounter) Collect(ch chan<- *MetricErr) {
values, err := rc.Rdb.HGetAll(context.Background(), rc.key()).Result()
if err != nil {
ch <- NewMetricErr(nil, err)
return
}
for field, value := range values {
v, _ := strconv.ParseFloat(value, 64)
constlabels := rc.constLabels(field)
metric := NewMetric(rc.Desc, v, constlabels)
ch <- NewMetricErr(metric, nil)
}
}
// Metric
func (rc redisCounter) Describe() *Desc {
return rc.Desc
}
// NewCounter ...
func NewCounter(rdb redis.Cmdable, opts CounterOptions) Counter {
desc := &Desc{
Namespace: opts.Namespace,
Name: opts.Name,
Help: opts.Help,
Type: CounterValue,
Labels: opts.Labels,
}
rc := redisCollector{
Rdb: rdb,
Desc: desc,
}
return &redisCounter{redisCollector: rc}
}