In this article, we will discuss about Spring Boot Actuator usage and configuration. We’ll explore creating a custom Actuator endpoint and modifying the default behavior of the health endpoint.
Why use Spring Boot Actuator?
Spring Boot Actuator is a project within the Spring Boot framework that provides features for monitoring and managing applications. It supports both HTTP and JMX for application monitoring and management.
Spring Boot Actuator offers several benefits that make it a valuable tool in a Spring Boot application. Here are some reasons why you should consider using Spring Boot Actuator:
- Monitoring and Health Checks: Spring Boot Actuator provides endpoints for monitoring and health checks of your application. You can easily obtain information about application health, system metrics, database connections, thread pools, and more. This helps you identify and resolve issues quickly, ensuring the smooth operation of your application.
- Production-Ready Features: Actuator includes various production-ready features such as metrics collection, request tracing, and logging configuration. These features allow you to gather insights into the performance and behavior of your application in a production environment.
- Operational Readiness: Actuator promotes operational readiness by providing endpoints for tasks like shutdown, restart, and configuration management. This allows you to control and manage your application remotely without requiring direct access to the server.
- Custom Endpoints: You can create custom endpoints to expose application-specific information or perform custom operations. This gives you flexibility in exposing additional management endpoints tailored to your application’s requirements.
- Security and Access Control: Actuator offers security features to protect sensitive information exposed by management endpoints. You can configure authentication and authorization rules to control access to Actuator endpoints, ensuring that only authorized users or systems can interact with management operations.
- Integration with Existing Monitoring Systems: Spring Boot Actuator integrates smoothly with various monitoring and management systems such as Prometheus, Grafana, ELK stack (Elasticsearch, Logstash, Kibana), and more. This allows you to leverage existing tools and frameworks to monitor and analyze application metrics and logs.
Configure Actuator in a Spring Boot application
To leverage the functionalities offered by Spring Boot Actuator, we need to add its Maven dependency to our application. Let’s explore the usage and configuration of Spring Boot Actuator:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Key Features
Actuator comes with most endpoints disabled by default, with only the /health
and /info
endpoints enabled.
One notable feature of Spring Actuator is its technology-agnostic nature, allowing it to be used with MVC or WebFlux as underlying technologies.
- Endpoints
- Metrics
- Auditing
Technology-Agnostic
One notable feature of Spring Actuator is its technology-agnostic nature, allowing it to be used with MVC or WebFlux as underlying technologies.
Endpoints
Actuator endpoints allow monitoring and interaction with the application. Additional endpoints can be created as needed, with each endpoint individually activatable or deactivatable.
Endpoints are accessed via the /actuator
prefix. For example, /health
provides basic application status information.
Metrics
Spring Boot Actuator provides metrics integration with Micrometer, a library for delivering Spring application metrics. It offers provider-agnostic interfaces for timers, meters, counters, distribution summaries, and long task timers with a dimensional data model.
Auditing
Spring Boot provides an auditing framework that publishes events to an AuditEventRepository. If using Spring Security, it automatically publishes authentication events.
Predefined Endpoints of Spring Boot Actuator
Here are some pre-defined endpoints that provide information about the application. It’s important to activate Actuator first.
- /auditevents: Lists security audit events, such as login.
- /beans: Lists all beans in the BeanFactory.
- /conditions: Generates a report of the conditions.
- /configprops: Provides all @ConfigurationProperties beans.
- /env: Returns the current property environment.
- /flyway: Provides information about Flyway database migrations.
- /health: Shows the application’s health status.
- /heapdump: Returns the JVM heap dump used by the application.
- /info: Provides general information.
- /liquibase: Similar to the Flyway endpoint but for Liquibase.
- /logfile: Application logs.
- /loggers: Allows querying and modifying log levels.
- /metrics: Returns application metrics.
- /prometheus: Returns metrics formatted for Prometheus.
- /scheduledtasks: Provides information about scheduled tasks.
- /sessions: Returns HTTP sessions used by Spring Session.
- /shutdown: Initiates the application shutdown.
- /threaddump: Returns JVM thread information.
How to customize an endpoint in Spring Boot Actuator?
Customize Health Endpoint
Since version 1 of Spring Boot, it has been possible to customize the /health endpoint by implementing the HealthIndicator class. However, with version 2, we can also implement it with the ReactiveHealthIndicator class and add reactive features to our /health endpoint.
@Component public class ServiceHealthIndicator implements ReactiveHealthIndicator { @Override public Mono<Health> health() { return webFluxServiceHealth().onErrorResume( service-> Mono.just(new Health.Builder().down(service).build()) ); } private Mono<Health> webFluxServiceHealth() { return Mono.just(new Health.Builder().up().build()); } }
As seen in the code snippet above, we have implemented a new Health indicator by overriding the methods of ReactiveHealthIndicator. This way, our /health endpoint becomes reactive.
Customize info:
For the /info endpoint, we can add Git details using the following dependency:
<dependency> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> </dependency>
We can also include build information such as name, group, and version using the Maven plugin:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>build-info</goal> </goals> </execution> </executions> </plugin>
Creating a Custom Endpoint
As mentioned earlier, Spring Boot Actuator allows us to create new endpoints. To generate a new endpoint, we create a new class that creates a bean and annotate it with @Endpoint
to indicate that it will create a new endpoint. The endpoint’s path is defined by the id
parameter of the @Endpoint
annotation.
Inside our endpoint, we can define different HTTP verbs using @ReadOperation
(HTTP GET), @WriteOperation
(HTTP POST), and @DeleteOperation
(HTTP DELETE).
Here’s an example:
@Component @Endpoint(id = "my-health") public class MyHealthEndpoint { Map<String, Object> healthMap = new LinkedHashMap<>(); @ReadOperation public Map<String, Object> health() { healthMap.put("MyHealth", "Working"); return healthMap; } @ReadOperation public String getHealth(@Selector String name) { return healthMap.get(name); } @WriteOperation public void writeOperation(@Selector String name) { //TODO this write operation } @DeleteOperation public void deleteOperation(@Selector String name){ //TODO delete operation } }
To access our endpoint, we can use the URL: http://host:port/actuator/my-health, and the output will be:
{ "MyHealth":"Working" }
Creating a Custom Endpoint in Controllers:
Apart from the previous method of creating endpoints, we have an alternative way to create custom endpoints using the @ControllerEndpoint
or @RestControllerEndpoint
annotations. With this approach, we can use the standard annotations like @RequestMapping
or @GetMapping
as we do in controllers.
Here’s an example:
@Component @RestControllerEndpoint(id = "controller-end-point") public class CustomEndPoint { @GetMapping("/my-endpoint") public @ResponseBody ResponseEntity customEndPoint(){ return new ResponseEntity<>("Something from my controller", HttpStatus.OK); } }
To call the new endpoint, we can use: http://host:port/actuator/controller-end-point/my-endpoint
Extending Existing Endpoints:
We can extend the behavior of a predefined endpoint using the @EndpointExtension
annotation.
@Component @EndpointWebExtension(endpoint = InfoEndpoint.class) public class InfoWebExtension { //TODO do something }
Activating All Endpoints:
As we have previously mentioned, not all endpoints of Spring Boot Actuator are defined for use and configuration. Only /health and /info are enabled by default. To activate them, we can do the following:
If we want to activate all endpoints:
management.endpoints.web.exposure.include=*
If we want to enable a specific endpoint:
management.endpoint.flyway.enabled=true
On the other hand, we can also activate all endpoints except one, for example, flyway:
management.endpoints.web.exposure.include=*management.endpoints.web.exposure.exclude=flyway
Conclusion
In conclusion, in this post, we have briefly explored the functioning of Spring Boot Actuator usage and configuration. We have seen how to extend certain endpoints for specific purposes.
If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!