Implementing Custom Actuator Endpoint
Spring Boot provides actuator endpoints that allows you to monitor or manage your application over JMX or HTTP. To add custom endpoint annotate Spring bean with @Endpoint
.
package org.example.demo.actuate;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
@Component
@Endpoint(id = "uptime") // (1)
public class UptimeEndpoint {
@ReadOperation // (2)
public Uptime getUptime() {
var runtime = ManagementFactory.getRuntimeMXBean();
return new Uptime(runtime.getUptime(), runtime.getStartTime());
}
private record Uptime(long uptime, long startTime) { }
}
@Endpoint
marks the class as Actuator endpoint. For HTTP endpointsid
specifies the path -actuator/uptime
in this example.@ReadOperation
marks the method as read operation. You can also use@WriteOperation
and@DeleteOperation
for respectively write and delete operations.
Accessing the endpoint:
$ curl 'http://localhost:8080/actuator/uptime' -i -X GET
would return the uptime in JSON format:
{"uptime":4056,"startTime":1717790421834}
For more information check the reference guide.
Troubleshooting
The code does not compile
Make sure that you have included the starter-actuator
dependency:
- Gradle
- Maven
build.gradle.kts
implementation("org.springframework.boot:spring-boot-starter-actuator")
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
/actuator/uptime returns 404 (Not Found)
Due to security considerations, most endpoint by default are disabled over HTTP. You can enable all endpoints (after you read the docs) by setting management.endpoints.web.exposure.include
:
application.properties
management.endpoints.web.exposure.include=*