feat: use random counter

This commit is contained in:
Artem Mezentsev 2025-04-13 14:58:05 +03:00
parent c6de46b8dc
commit 46a2c1c8f3
2 changed files with 27 additions and 30 deletions

View File

@ -1,4 +0,0 @@
apiVersion: v1
kind: Namespace
metadata:
name: metrics-counter

53
main.go
View File

@ -1,11 +1,12 @@
package main
import (
"context"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
@ -13,32 +14,26 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
counter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "custom_counter_total",
Help: "A counter that increments every 30 seconds",
},
[]string{},
)
counterValue uint64
var counter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "random_counter_total",
Help: "A counter that increments randomly from 1 to 30 seconds",
},
[]string{},
)
func main() {
// Register Prometheus metrics
prometheus.MustRegister(counter)
// Start background counter incrementer
go incrementCounterEvery30s()
// Set up HTTP server
http.Handle("/metrics", promhttp.Handler())
server := &http.Server{Addr: ":8080"}
// Handle graceful shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go startCounting(ctx)
go func() {
log.Println("Starting server on :8080")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
@ -46,17 +41,23 @@ func main() {
}
}()
<-stop
log.Println("\nShutting down server...")
<-ctx.Done()
log.Println("Shutdown the server")
// Give one more second for gracefully shutdown
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
server.Shutdown(ctx)
}
func incrementCounterEvery30s() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
newVal := atomic.AddUint64(&counterValue, 1)
counter.WithLabelValues().Add(1)
log.Printf("Counter incremented to %d", newVal)
func startCounting(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
counter.WithLabelValues().Add(1)
sleepDuration := time.Duration(rand.Intn(29) + 1)
time.Sleep(sleepDuration * time.Second)
}
}
}