Spring Boot Actuator

In this post, we will introduce and cover Spring Boot Actuator.We will be covering various features and end point of Spring Boot Actuator.

 

Introduction

Spring Boot Actuator is available from the very first release of Spring Boot.These are additional features to help us check and manage our application.Before we dive into the details, let’s understand what actually is an actuator?

 

1. What is Spring Boot Actuator

The actuator provides production-ready features for Spring Boot application.It will help us to check and manage our application in the production environment.We don’t need any code to get these features since they are available once the actuator dependency is in the class-path.The actuator provides features like auditing, health, metrics, environment information, thread dump etc. using HTTP endpoints.

 

2. Enabling Actuator in Spring Boot

All the actuators production-grade features provided through the spring-boot-actuator starter.To enable these features in our application, we need to add spring-boot-starter-actuator in the pom.xml file (refer to the official documentation if you are using Gradle or any other build tool)

<dependencies>
   <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
   </dependency>
</dependencies>

 

3. Spring Boot 1.x vs 2.x Actuator

Spring Boot 2.x brings important changes to Actuator which are different from Spring Boot 1.x.Boot 1.x web endpoints only supported with Spring MVC while 2.x provides support for Spring MVC, Spring WebFlux, and Jersey.We are splitting this post into two sections

  • Spring Boot 1.x Actuator
  • Spring Boot 2.x Actuator

 

4. Spring Boot 1.x  Actuator

Spring Boot 1.x Actuator provides features using HTTP endpoints, JMX or remote shell scrips (SSH etc.).Spring Boot 1.x is based on  R/W model, this means we can only perform read and write operations.Let’s see what is meant by R/W model

  • We can read application health information or read/fetch metrics information. (Read operation)
  • Shutdown application node (write operation)

 

4.1. Endpoints

Actuator endpoints allow you to monitor and interact with your application. Spring Boot includes a number of built-in endpoints and you can also add your own.Spring Boot enables certain security restriction if the endpoints are sensitive.The sensitive endpoints will need a username/password when accessed over HTTP (or simply disabled if web security is not enabled).

 

4.2. Available Endpoints

Here is the list of the popular endpoints provided by Spring Boot Actuator

  • /beans – Displays a complete list of all the Spring beans in your application.
  • /metrics – Shows ‘metrics’ information for the current application.
  • /health – Shows application health information.
  • /trace – Displays trace information (by default the last 100 HTTP requests).
  • /info – Displays arbitrary application info.
  • /dump – Performs a thread dump.

Refer to the official docs for the complete list of the out of box endpoints.

 

4.3. Customizing Endpoints

Spring Boot provides an option to customize endpoints using spring.properties file.It uses the prefix endpoints + . + name  to uniquely identify the endpoint being configured.Keep in mind following three important properties while customizing endpoints for your Spring Boot application.

  • id – Id is the endpoint mapped to URL.
  • sensitive – property for security hint.The sensitive endpoints (if set true) require a username/password when accessed over HTTP.
  • enabled – endpoint can only be accessed if this property set to true.

Most of the endpoints in Spring Boot 1.x are enabled by default except shutdown.

For example, to change the sensitivity and id of the beans endpoint

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false

Let’s take a look at some of the most commonly used endpoints available with Spring Boot Actuator.

 

4.4. /bean Endpoint

The bean endpoint displays a complete list of all the Spring Bean in our application.This endpoint provides information like bean name, aliases, bean scope, bean type (class name), bean dependencies.The /bean endpoints give a snapshot of the Spring IoC container.Here is the out of the box output for this endpoint.

{
   "context":"application",
   "parent":null,
   "beans":[
      {
         "bean":"restdemoApplication",
         "aliases":[

         ],
         "scope":"singleton",
         "type":"com.javadevjournal.rest.RestdemoApplication$$EnhancerBySpringCGLIB$$671e6931",
         "resource":"null",
         "dependencies":[

         ]
      },
      {
         "bean":"org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory",
         "aliases":[

         ],
         "scope":"singleton",
         "type":"org.springframework.core.type.classreading.CachingMetadataReaderFactory",
         "resource":"null",
         "dependencies":[

         ]
      }
   ]
}
 
4.5. /metrics Endpoint

The metrics endpoint publishes information about the current application which includes  OS, JVM information, memory and heap information, thread pool etc.Here is the out of the box output for this endpoint.

{
   "mem":356345,
   "mem.free":131928,
   "processors":8,
   "instance.uptime":1890672,
   "uptime":1893143,
   "heap.committed":313856,
   "heap.init":262144,
   "heap.used":181927,
   "heap":3728384,
   "threads.peak":40,
   "threads.daemon":24,
   "threads.totalStarted":52,
   "threads":26,
   "httpsessions.max":-1,
   "httpsessions.active":0,
   "gauge.response.beans":20.0,
   "gauge.response.env":8.0,
   "gauge.response.dump":71.0,
   "gauge.response.metrics":50.0,
   "gauge.response.health":9.0,
   "gauge.response.info":11.0
}

/metrics endpoints also provide the feature to get information about a specific metric.To get information about a specific metrics, make a GET request using /metrics/{metric.name}

curl 'http://localhost:8080/metrics/mem.free' -i

The response will provide information about the specific metric

HTTP/1.1 200 
X-Application-Context: application
Content-Disposition: inline;filename=f.txt
Content-Type: application/vnd.spring-boot.actuator.v1+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 01 Apr 2018 22:02:17 GMT
{
   "mem.free":124997
}
 
4.6. /health Endpoint

The /health endpoint is to check the health or state of the running application.Here is the out of the box output for this endpoint.

{
   "status":"UP",
   "diskSpace":{
      "status":"UP",
      "total":499963170816,
      "free":362682060800,
      "threshold":10485760
   }
}
 
4.7. /info Endpoint

The info endpoint displays arbitrary application info.We can customize the data shown in the info endpoint using application.properties file.

info.app.name=Spring Actuator Sample Application
info.app.description=Application to demonstarte features and capabilities of Spring Boot Actuator 
info.app.version=1.0.0

Here is the output for this endpoint.

{
  "app":{
     "description":"Application to demonstarte features and capabilities of Spring Boot Actuator ",
     "name":"Spring Actuator Sample Application",
     "version":"1.0.0"
   }
}
 
4.8. /dump Endpoint

The dump endpoint displays a thread dump for our application.This is really helpful if we want to debug our application and need thread dump of the running application.Here is the out of the box output for this endpoint.

{
   "threadName":"RMI TCP Connection(idle)",
   "threadId":61,
   "blockedTime":-1,
   "blockedCount":0,
   "waitedTime":-1,
   "waitedCount":1,
   "lockName":"java.util.concurrent.SynchronousQueue$TransferStack@2be5e1c8",
   "lockOwnerId":-1,
   "lockOwnerName":null,
   "inNative":false,
   "suspended":false,
   "threadState":"TIMED_WAITING",
   "stackTrace":[
      {
         "methodName":"park",
         "fileName":"Unsafe.java",
         "lineNumber":-2,
         "className":"sun.misc.Unsafe",
         "nativeMethod":true
      },
      {
         "methodName":"parkNanos",
         "fileName":"LockSupport.java",
         "lineNumber":215,
         "className":"java.util.concurrent.locks.LockSupport",
         "nativeMethod":false
      }
   ]
}
 
4.9. Implementing Custom Endpoints

To implement a new endpoint for our application, we should expose the instance of the custom endpoint class as a bean.We need to implement Endpoint<T> interface.

@Component
public class CustomEndpoint implements Endpoint {
    @Override
    public String getId() {
        return "custom-endpoint";
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public boolean isSensitive() {
        return false;
    }

    @Override
    public String invoke() {
        return "This is a custom end point for demo purpose";
    }
}

To access our custom endpoint, use the id field (for our example, it is “custom-endpoint“).Use /custom-endpoint to check the output.

{This is a custom end point for demo purpose}
 
4.10. Additional Customization

Spring Boot Actuator provides a number of options for the additional customization using application.properties file.Below are some of the important properties to customize Actuator.

#Disable security feature for all end points.By default all sensitive HTTP endpoints are secure.
management.security.enabled=false

#Customizing the management endpoint paths.All endpoints will be accessible through manage/endpoint
management.context-path=/manage

#Property to configure /change management server port.All endpoints will be accessible only through this port
management.port=9001

#customize the address that the management endpoints. 
management.address=127.0.0.1

#disable endpoint over HTTP
management.port=-1

Actuator endpoints (with property sensitive as true) are secured.We can use Spring Boot application.properties file to change the username and password and the security role(s) required to use the endpoints.

security.user.name=admin
security.user.password=secret
management.security.roles=SUPERUSER
 
4.11. The Limitation with Actuator 1.x

The Actuator comes with many powerful tools, however, 1.x has certain limitations.

  • The web endpoints in the Actuator are only supported with Spring MVC.
  • To support Jax-RS, we will need to enable Spring MVC. 
  • Creating a new endpoint is not simple and requires writing a lot of boilerplate.

 

4.12. Actuator and Jersey

Actuator 1.x endpoints are only available for Spring MVC.To use Jersey for your application, follow these steps

  • Enable Spring MVC by using spring-boot-starter-web starter.
  • Change mapping for the dispatcher servlet by using spring.jersey.application-path property in the application.properties file.

 

5. Spring Boot 2.x Actuator

Spring Boot 2 brings important changes to Actuator.Here are the most important key points for Spring Boot 2.x Actuator.

  • Support for Spring MVC, Spring Webflux, and Jersey.
  • Native support for Jersey.
  • Pluggable and extensible without relying only on Spring MVC.
  • The new @Endpoint annotation to define endpoints.
  • JMX MBean support is still there and needs no additional code. 

 

5.1. Important Changes

There are numbers of changes introduced in the Actuator 2.x.If you are migrating from Spring Boot 1.x to 2.x, these are really important as some of the changes introduced in the Actuator are breaking.

  • This version support CURD model as compared to R/W under 1.x
  • All Actuator endpoints are now placed under the /actuator path.
  • Spring Boot 2.0 no longer ships with its own metrics APIs. Instead, it relies on micrometer.io for all application monitoring needs.

New Actuator API is more aligned with the application security rules which made it simple to configure security aspects for the endpoints.We can enable access to all the endpoints using application.properties 

#All our actuator endpoints can be accessed without requiring authentication
management.endpoints.web.exposure.include=*

We would need to add custom security configuration that allows unauthenticated access to the endpoints if Spring Security is present.Please refer to the documentation for the list of out of the box endpoints

 

5.2. Custom Endpoint

Spring Boot 2 provides an easy way to create custom endpoints.Spring Boot 2.x introduced @Endpoint annotation. The @Endpoint annotation can be used in combination with @ReadOperation,@WriteOperation and @DeleteOperation to develop endpoints

@Component
@Endpoint(id = "custom-endpoint")
public class CustomEndpoint{

    @ReadOperation
    public String custom() {
        return "custom-end-point";
    }

    @ReadOperation
    public String customEndPointByName(@Selector String name) {
        return "custom-end-point";
    }

    @WriteOperation
    public void writeOperation(@Selector String name) {
        //perform write operation
    }
   @DeleteOperation
   public void deleteOperation(@Selector String name){
    //delete operation
  }
}

Let’s take a closer look at the new conventions and annotation introduced in Spring Boot 2.x Actuator.

  • The Id property of the @Endpoint annotation determines the mapping of our endpoint (in our example it is /custom-endpoint).
  • @ReadOperation – HTTP Get method.
  • @WriteOperation – POST method.
  • @DeleteOperation – HTTP DELETE operation.

 

5.2. Extending Existing Endpoints

With 2.x, it is easy to extend the behavior of an existing endpoint with the help of @EndpointExtension annotation.Let’s take an example of CustomHealthEndpoint where we want to send custom status code as part of the web endpoint.To achieve this we use @EndpointWebExtension annotation.

 

Summary

In this article, we discussed Spring Boot Actuator.We covered different features introduced with Spring Boot 1.x Actuator along some limitations.In the second part of this article, we covered new features and improvement introduced in Spring Boot 2.x Actuator.

Leave a Reply

2 Comments on "Spring Boot Actuator"

avatar
  Subscribe  
newest oldest most voted
Notify of
Shaswat
Guest

Please correct the spelling of “Spring boot” in section 3 under 3. Spring Boot 1.x vs 2.x Actuator.

Thanks 🙂

Umesh Awasthi
Admin

Done.Thanks for the pointer 🙂