How to Integrate Prometheus Monitoring into Spring Boot with Grafana
This guide walks through setting up Prometheus and Grafana to monitor a Spring Boot 2.3.11 application, covering environment preparation, Maven dependencies, Spring configuration, custom metrics, Prometheus server setup, and visualizing data in Grafana.
What is Prometheus
Prometheus is an open‑source service monitoring system and time‑series database.
It stores time‑series data identified by a metric name and a set of key/value labels.
Configuration Dependencies
<code><dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
</dependencies></code> <code>spring:
application:
name: app-prometheus
---
management:
server:
port: 9999
endpoints:
enabled-by-default: true
web:
exposure:
include: '*'</code>Register MeterRegistry
<code>@Bean
public MeterRegistryCustomizer<MeterRegistry> configurer(@Value("${spring.application.name}") String name) {
return registry -> registry.config().commonTags("application", name);
}</code>Access Prometheus actuator endpoint at
http://localhost:9999/actuator/prometheus.
Prometheus Installation & Configuration
Download Prometheus from the official site.
Configure
prometheus.yml:
<code>scrape_configs:
- job_name: 'app-prometheus'
scrape_interval: 5s
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['localhost:9999']</code>Start Prometheus and open its UI to view collected metrics.
Custom Meter Example
<code>@Resource
private MeterRegistry registry;
private Counter counter;
@PostConstruct
public void init() {
counter = this.registry.counter("visitor");
}
@GetMapping("/count")
public String count() {
this.counter.increment();
return "访问次数:" + this.counter.count();
}</code>Invoke the
/countendpoint several times and observe the incremented metric in Prometheus.
Grafana Installation & Configuration
Download and start Grafana (default credentials admin/admin).
Add Prometheus as a data source pointing to
http://localhost:9090.
Create dashboards to visualize the
visitormetric and other application metrics.
Monitoring Database Connection Pool
When using HikariCP in the Spring Boot project, Grafana can automatically display database connection pool statistics after adding the Prometheus data source.
All steps complete – you now have a fully monitored Spring Boot application with Prometheus and Grafana.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.