0Pricing
Spring Boot 4 Microservices & REST APIs · Lezione

Metriche personalizzate con Micrometer

Registri le metriche personalizzate dell'applicazione.

Metriche personalizzate con Micrometer è una lezione Spring Boot 4 Microservices & REST APIs gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Microservices & REST APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Micrometer: The Metrics Facade

Spring Boot uses Micrometer as a vendor-neutral metrics facade — the SLF4J of metrics. You instrument code against one API, then export to Prometheus, Datadog, CloudWatch, and others by adding a registry.

The MeterRegistry

The central component is the MeterRegistry. Boot auto-configures one and registers it as a bean, so you simply inject it wherever you need to record measurements.

@Service
public class OrderService {
    private final MeterRegistry registry;
    public OrderService(MeterRegistry registry) {
        this.registry = registry;
    }
}

Counters

A Counter records a value that only increases — perfect for counting events like orders placed or errors encountered. Create it once and increment it as events occur.

@Service
public class OrderService {
    private final Counter ordersPlaced;
    public OrderService(MeterRegistry registry) {
        this.ordersPlaced = registry.counter("orders.placed");
    }
    public void place(Order o) {
        // ... business logic
        ordersPlaced.increment();
    }
}

Tags (Dimensions)

Add tags to slice a metric by dimension — channel, region, status. Each unique tag combination is a separate time series, so keep tag cardinality bounded.

registry.counter("orders.placed",
        "channel", "web",
        "region", "eu")
    .increment();

Timers

A Timer measures both how often something happens and how long it takes, yielding count, total time, and max. Use it to track operation latency.

Timer timer = registry.timer("orders.process.time");
timer.record(() -> processOrder(order));

Recording Time Manually

When you cannot wrap the work in a lambda, capture a Timer.Sample at the start and stop it against a timer at the end.

Timer.Sample sample = Timer.start(registry);
try {
    processOrder(order);
} finally {
    sample.stop(registry.timer("orders.process.time"));
}

Gauges

A Gauge reports a value that can go up or down — a queue depth, active sessions, cache size. You register a function that Micrometer samples on demand.

registry.gauge("orders.queue.size",
    orderQueue, q -> q.size());

Distribution Summaries

A DistributionSummary tracks the distribution of arbitrary values, such as request payload sizes, providing count, total, and percentiles.

DistributionSummary summary = registry.summary("orders.amount");
summary.record(order.getTotal().doubleValue());

Declarative Timing with @Timed

The @Timed annotation times a method without manual instrumentation. It requires a TimedAspect bean to be registered.

@Bean
TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
}

@Timed(value = "orders.process.time")
public void process(Order o) { /* ... */ }

Exporting to Prometheus

Add the Prometheus registry dependency and expose the prometheus endpoint. Micrometer then publishes a scrape endpoint with all your meters.

# dependency: micrometer-registry-prometheus
management:
  endpoints:
    web:
      exposure:
        include: prometheus,metrics,health
# scrape: /actuator/prometheus

Cardinality Discipline

The biggest metrics pitfall is high-cardinality tags. Never tag with user ids, request ids, or raw URLs — each unique value multiplies time series and can overwhelm your backend.

Quick Check

Test your understanding of meter types.

Recap

Micrometer instruments your app.

  • Inject the auto-configured MeterRegistry
  • Counter for monotonic counts, Timer for latency
  • Gauge for fluctuating values, DistributionSummary for distributions
  • Use bounded tags; avoid high cardinality
  • Export to Prometheus and friends via a registry dependency

Domande Frequenti

La lezione «Metriche personalizzate con Micrometer» è gratuita?

Sì — il testo completo di «Metriche personalizzate con Micrometer» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Microservices & REST APIs, passa a CoddyKit PRO. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Cosa imparerò in «Metriche personalizzate con Micrometer»?

Registri le metriche personalizzate dell'applicazione. Eserciti Spring Boot 4 Microservices & REST APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Microservices & REST APIs?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Microservices & REST APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Metriche personalizzate con Micrometer»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Microservices & REST APIs?

Sì. Ogni lezione Spring Boot 4 Microservices & REST APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Abilitare gli endpoint Actuator
  2. Indicatori di salute
  3. Metriche personalizzate con Micrometer
  4. Proteggere gli endpoint Actuator
← Torna a Spring Boot 4 Microservices & REST APIs