Prometheus in Spring Boot


Prometheus is an open-source monitoring and alerting toolkit (part of the CNCF ecosystem).

  • Supervision in this context usually refers to supervising processes or services using Prometheus.
  • Prometheus collects metrics from services and systems, stores them, and lets you set up alerts (via Alertmanager) to supervise the health of your infrastructure.
  • Example: CPU usage, memory consumption, request latency, or service availability can be “supervised” by Prometheus metrics and rules.

So here, Prometheus supervision means using Prometheus as a supervisory system for observing and ensuring services are healthy.


2. Configure Spring Boot for Prometheus

In application.properties:

# Enable actuator endpoints
management.endpoints.web.exposure.include=health,info,prometheus
management.endpoint.prometheus.enabled=true

This will expose Prometheus metrics at:

http://localhost:8080/actuator/prometheus

3. Add a Sample REST Controller

package com.example.demo.controller;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    private final MeterRegistry meterRegistry;

    public HelloController(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    @GetMapping("/hello")
    public String hello() {
        // Increment a custom counter
        meterRegistry.counter("hello_requests_total").increment();
        return "Hello, Spring Boot with Prometheus!";
    }
}
  • Here, we create a custom metric hello_requests_total.
  • Every time /hello is called, the counter increases.

4. Run the Spring Boot Application

Run the app using:

./gradlew bootRun

Access metrics at:

http://localhost:8080/actuator/prometheus

You should see metrics like:

# HELP hello_requests_total_total 
# TYPE hello_requests_total_total counter
hello_requests_total_total 3.0

5. Configure Prometheus

Create a prometheus.yml file:

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'spring-boot-app'
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['host.docker.internal:8080']  # use localhost if running locally

Run Prometheus with:

docker run -p 9090:9090 -v $PWD/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

Prometheus will start scraping your Spring Boot metrics.


6. Visualize Metrics with Grafana (Optional)

You can also run Grafana:

docker run -d -p 3000:3000 grafana/grafana
  • Add Prometheus as a data source.
  • Build dashboards using hello_requests_total or other metrics.

Summary

  • Spring Boot actuator exposes metrics.
  • Micrometer Prometheus registry allows Prometheus scraping.
  • Custom counters/timers can be added.
  • Prometheus scrapes /actuator/prometheus.
  • Grafana can visualize metrics.

Leave a Reply