mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2024-11-21 14:44:00 +00:00
lib/httpserver: cache /metrics
output for a second
This should reduce CPU load when `/metrics` output is scraped with a frequency exceeding a request per second
This commit is contained in:
parent
7869d38043
commit
18305caadb
1 changed files with 24 additions and 0 deletions
|
@ -6,9 +6,12 @@ import (
|
|||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/VictoriaMetrics/VictoriaMetrics/lib/buildinfo"
|
||||
"github.com/VictoriaMetrics/VictoriaMetrics/lib/bytesutil"
|
||||
"github.com/VictoriaMetrics/VictoriaMetrics/lib/flagutil"
|
||||
"github.com/VictoriaMetrics/VictoriaMetrics/lib/memory"
|
||||
"github.com/VictoriaMetrics/metrics"
|
||||
|
@ -18,6 +21,27 @@ var versionRe = regexp.MustCompile(`v\d+\.\d+\.\d+`)
|
|||
|
||||
// WritePrometheusMetrics writes all the registered metrics to w in Prometheus exposition format.
|
||||
func WritePrometheusMetrics(w io.Writer) {
|
||||
currentTime := time.Now()
|
||||
metricsCacheLock.Lock()
|
||||
if currentTime.Sub(metricsCacheLastUpdateTime) > time.Second {
|
||||
var bb bytesutil.ByteBuffer
|
||||
writePrometheusMetrics(&bb)
|
||||
metricsCache.Store(&bb)
|
||||
metricsCacheLastUpdateTime = currentTime
|
||||
}
|
||||
metricsCacheLock.Unlock()
|
||||
|
||||
bb := metricsCache.Load().(*bytesutil.ByteBuffer)
|
||||
w.Write(bb.B)
|
||||
}
|
||||
|
||||
var (
|
||||
metricsCacheLock sync.Mutex
|
||||
metricsCacheLastUpdateTime time.Time
|
||||
metricsCache atomic.Value
|
||||
)
|
||||
|
||||
func writePrometheusMetrics(w io.Writer) {
|
||||
metrics.WritePrometheus(w, true)
|
||||
metrics.WriteFDMetrics(w)
|
||||
|
||||
|
|
Loading…
Reference in a new issue