Introduction
Monitoring and observability are crucial aspects of modern application development. Prometheus is a popular open-source monitoring and alerting toolkit designed for reliability and scalability. In this tutorial, we will explore how to integrate Prometheus with a Spring Boot application to monitor and collect metrics.
Prerequisites
Before starting, make sure you have the following installed:
- Java Development Kit (JDK) 8 or later
- Maven
- Prometheus (download from Prometheus official website)
Step 1: Create a Spring Boot Project
Create a new Spring Boot project using Spring Initializer or your preferred IDE. Include the “Spring Web” dependency.
If using Spring Initializer, you can add dependencies like this:
- Group: com.example
- Artifact: spring-boot-prometheus
- Dependencies: Spring Web
Step 2: Add Prometheus Dependency
Open the pom.xml
file of your project and add the Prometheus dependency:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
This dependency includes the Micrometer Prometheus registry, which allows us to expose metrics in a format that Prometheus can scrape.
Step 3: Configure Prometheus Properties
In your application.properties
or application.yml
file, add the following configuration:
# Prometheus Configuration
management.endpoints.web.exposure.include=*
management.endpoint.metrics.enabled=true
management.metrics.export.prometheus.enabled=true
This configuration opens up all available endpoints for monitoring and enables Prometheus to scrape metrics.
Step 4: Create a Sample Controller
Create a simple controller to generate some metrics. For example, create a SampleController.java
:
Step 5: Run the Application
Run your Spring Boot application. Visit http://localhost:8080/api/hello
to trigger the /hello
endpoint.
Step 6: Access Prometheus Dashboard
Now, access the Prometheus dashboard by visiting http://localhost:9090
. In the query input box, you can enter queries to retrieve metrics. For example, try the query http_server_requests_seconds_count
to see the count of HTTP server requests.
Step 7: Grafana Integration (Optional)
Optionally, you can integrate Grafana for better visualization of Prometheus metrics. Download and install Grafana from Grafana official website.
Add Prometheus as a data source in Grafana, and create dashboards to visualize and analyze your application metrics.
Conclusion
You have successfully integrated Prometheus with your Spring Boot application for monitoring and collecting metrics. You can further explore advanced configurations, custom metrics, and Grafana dashboards to enhance your monitoring capabilities.