“Spring Boot Actuator in Detail and In-depth Application” is expected to include three chapters. The first chapter focuses on the application and customization of Spring Boot Actuator 1.x. In the second part, compare the differences between Spring Boot Actuator 2.x and 1.x, and apply and customize 2.x endpoints. In chapter 3, the use of Actuator Metric metrics in conjunction with Prometheus and Grafana will be described. This part of the content is very common, and more introductory, welcome your attention.

What is the physical

Spring Boot Actuators provide features commonly used in production (such as health checks, auditing, metrics collection, HTTP tracking, etc.) to help us monitor and manage Spring Boot applications. All of these functions can be accessed via JMX or HTTP endpoints.

By introducing related dependencies, we can monitor our application, making it easy to gather metrics and understand the state of traffic or databases. The main benefit of this library is that we can get production-grade tools without actually implementing the functionality ourselves. As with most Spring modules, it can be easily configured or extended in a number of ways.

The Actuator can also be integrated with external application monitoring systems such as Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic, and more. These systems provide you with excellent dashboards, graphics, analytics and alerts to help us monitor and manage application services in a unified interface.

In this article, Spring Boot Actuator 1.x includes endpoints (HTTP endpoints), configuration management, and extension and customization endpoints.

Quick start

Introduce the following dependencies:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
Copy the code

Spring Boot Actuator 1.x

In 1.x, the Actuator follows the read-write model, which means we can read and write information from it. We can retrieve metrics or the health of our application, and of course we can gracefully terminate our application or change our logging configuration. The Actuator exposes its HTTP endpoints through Spring MVC.

The endpoint

When the imported Actuator version is 1.x, the application service is started and the console outputs the following endpoint information:

Here are some common endpoints:

  • /health: Displays application health information (simple “status” when accessed over an unauthenticated connection or full message details when authenticated), which is insensitive by default
  • /info: displays application information, not sensitive by default
  • /metrics: Displays “metrics” information for the current application, which is also sensitive by default
  • /trace: Displays trace information (the last HTTP requests by default)

Some endpoints are not enabled by default, such as /shutdown.

Configure the endpoint

We can customize the attributes for each endpoint in the following format:

endpoints.[endpoint name].[property to customize]
Copy the code

The following three attributes can be customized:

  • Id, the exposed HTTP endpoint address
  • Enabled: Whether to enable it
  • Sensitive: When this parameter is true, sensitive information is obtained through HTTP only after authentication

We added the following configuration to the configuration file to customize the/Beans endpoints.

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
endpoints.beans.enabled=true
Copy the code

/ health endpoint

The /health endpoint monitors the status of the running service instance and notifies O&M when the service instance goes offline or becomes abnormal for other reasons (such as DB connection failure or disk space shortage).

By default, HTTP returns only the following simple information:

{
	"status": "UP"
}
Copy the code

Get detailed health information

We do the following configuration:

endpoints:
  health:
    id: chealth
    sensitive: false

management.security.enabled: false
Copy the code

As described in the previous section, we changed the access path for the/Health endpoint to /chealth and turned security authorization off. Visit http://localhost:8005/chealth will get the following results.

{
	"status": "UP"."healthCheck": {
		"status": "UP"
	},
	"diskSpace": {
		"status": "UP"."total": 999995129856,
		"free": 762513104896,
		"threshold": 10485760}}Copy the code

Customize health information

We can also customize the implementation of the Health indicator. It can collect any type of custom health data specific to the application and access the defined information through the/Health endpoint.

@Component
public class HealthCheck implements HealthIndicator {

    @Override
    public Health health(a) {
        int errorCode = check(); // perform some specific health check
        if(errorCode ! =0) {
            return Health.down()
                    .withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    public int check(a) {
        // Our logic to check health
        return 0; }}Copy the code

To customize our/Health endpoint, implement the HealthIndicator interface and override the health() method within it.

/ info endpoint

With the/INFO endpoint, we can define some basic information for the application service:

info.app.name=Spring Sample Application info.app.description=This is my first spring boot application Info. App. Version = 1.0.0Copy the code

We defined the service name, description, and version number of the service in the above configuration.

/ metrics endpoint

The /metrics endpoint shows OS, JVM, and application level metrics. When enabled, we can get information about memory, heap, threads, thread pools, class loads, and HTTP.

{
	"mem": 417304,
	"mem.free": 231678,
	"processors": 4."instance.uptime": 248325,
	"uptime": 250921,
	"systemload.average": 1.9541015625."heap.committed": 375296,
	"heap.init": 393216,
	"heap.used": 143617,
	"heap": 5592576,
	"nonheap.committed": 43104,
	"nonheap.init": 2496,
	"nonheap.used": 42010,
	"nonheap": 0."threads.peak": 30."threads.daemon": 18."threads.totalStarted": 46."threads": 20."classes": 6020,
	"classes.loaded": 6020,
	"classes.unloaded": 0."gc.ps_scavenge.count": 3."gc.ps_scavenge.time": 35."gc.ps_marksweep.count": 1,
	"gc.ps_marksweep.time": 29."httpsessions.max": 1,"httpsessions.active": 0."gauge.response.info": 38.0."counter.status.200.info": 1}Copy the code

Customizing metrics endpoints

In order to collect customized metrics, the Actuator supports single-value recording and can simply add and subtract counts. In the following implementation, we record the number of login successes and failures as a custom metric.

@Service
public class LoginServiceImpl implements LoginService {
    private final CounterService counterService;

    @Autowired
    public LoginServiceImpl(CounterService counterService) {
        this.counterService = counterService;
    }

    @Override
    public Boolean login(String userName, char[] password) {
        boolean success;
        if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
            counterService.increment("counter.login.success");
            success = true;
        } else {
            counterService.increment("counter.login.failure");
            success = false;
        }
        returnsuccess; }}Copy the code

Visit /metrics again and find the following metrics information. Login attempts and other security-related events can be used as audit events in the Actuator.

{
	"gauge.response.metrics": 2.0."gauge.response.test": 3.0."gauge.response.star-star.favicon.ico": 1.0."counter.status.200.star-star.favicon.ico": 10,
	"counter.status.200.test": 6,
	"counter.login.failure": 6,
	"counter.status.200.metrics"4} :Copy the code

Custom endpoints

In addition to using the endpoints provided by Spring Boot Actuators, we can also define a brand new endpoint.

First, we need to implement the Endpoint interface:

@Component
public class CustomEndpoint implements Endpoint<List<String>> {
    @Override
    public String getId(a) {
        return "custom";
    }

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

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

    @Override
    public List<String> invoke(a) {
        // Custom logic to build the output
        List<String> messages = new ArrayList<String>();
        messages.add("This is message 1");
        messages.add("This is message 2");
        returnmessages; }}Copy the code

The getId() method is used to match access to this endpoint, and invoke() our custom logic will be called when we access/Custom. The other two methods are used to set whether to open and whether to be sensitive endpoints.

[ "This is message 1"."This is message 2" ]
Copy the code

Further customization

For security, we may choose to expose the endpoints of the Actuator through non-standard ports. It is configured through the management.port property.

Additionally, as we have already mentioned, in 1.x. Actuator configures its own Security model based on Spring Security, but independent of the rest of the application.

Therefore, we can change the management-address attribute to limit where the endpoint can be accessed over the network:

#port used to expose actuator
management.port=8081 
 
#CIDR allowed to hit actuator
Management. The address = 127.0.0.1 
Copy the code

In addition, all endpoints except /info endpoints are sensitive by default, and if Spring Security is introduced, we secure the built-in endpoints by defining these Security attributes (Username, Password, role) in the configuration file.

conclusion

Spring Boot Actuators provide many out-of-the-box features for our application services in production environments. This article mainly introduces the in-depth use of Spring Boot Actuator 1.x. We can either use built-in endpoints (such as /health, /info, etc.), which can be extended and customized from these endpoints, or we can customize brand new endpoints, which is very flexible in how we use them. Source: github.com/keets2012/S…

Subscribe to the latest articles, welcome to follow my official account

reference

  1. Actuator docs
  2. Spring Boot Actuator