Write a code for java on spring boot for collecting metric fro, server
- User
Write a code for java on spring boot for collecting metric fro, server
- Assistant
Creating a Spring Boot application that collects server metrics involves setting up an Actuator, which is a sub-project of Spring Boot. Actuator enables production-ready features such as monitoring and managing your application. The following example demonstrates how to create a basic Spring Boot application with Actuator to collect server metrics.
Step 1: First, create a new Spring Boot project using the Spring Initializr or your preferred method.
Step 2: Add the Spring Boot Actuator and Micrometer dependencies to your
build.gradlefile:dependencies { implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'io.micrometer:micrometer-registry-prometheus' testImplementation 'org.springframework.boot:spring-boot-starter-test' }Adjust the dependencies according to your build tool (Maven, Gradle, etc.).
Step 3: Configure the Actuator settings in
src/main/resources/application.propertiesfile:management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always management.metrics.export.prometheus.enabled=trueThis configuration will expose all available Actuator endpoints via HTTP and enable Prometheus support for metrics collection.
Step 4: Create a simple REST Controller to demonstrate the metrics collection. In
src/main/java/com/example/metricsexample/HelloController.java:package com.example.metricsexample; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, Spring Boot Metrics!"; } }Step 5: Run your Spring Boot application:
./gradlew bootRunStep 6: Test your application with a few requests:
curl http://localhost:8080/helloStep 7: Access the metrics endpoint:
curl http://localhost:8080/actuator/metricsYou can view the collected metrics, including JVM stats, application stats such as REST request count, and more.