Home > Java > javaTutorial > body text

A Beginners Guide to Using Spring Boot Actuator

WBOY
Release: 2024-08-02 10:00:24
Original
754 people have browsed it

A Beginners Guide to Using Spring Boot Actuator

Spring Boot Actuator is a sub-project of Spring Boot that provides production-ready features to help you monitor and manage your application. It offers a set of built-in endpoints that allow you to gain insights into your application's health, metrics, and environment, as well as control it dynamically.

What is Spring Boot Actuator?

Spring Boot Actuator provides several out-of-the-box endpoints that can be used to monitor and interact with your application. These endpoints can be accessed over HTTP, JMX, or using Spring Boot Admin.

Key Features of Spring Boot Actuator

  1. Health Checks: Monitor the health of your application and its dependencies.
  2. Metrics: Collect various metrics such as memory usage, garbage collection, web request details, etc.
  3. Environment Information: Access the application's environment properties.
  4. Application Information: Retrieve information about the application's build, such as version and name.
  5. Dynamic Log Levels: Change log levels without restarting the application.
  6. HTTP Tracing: Trace HTTP requests.

Setting Up Spring Boot Actuator

1. Adding Actuator Dependency

To use Actuator in your Spring Boot application, you need to add the Actuator dependency to your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy after login

If you are using Gradle, add the following to your build.gradle file:

implementation 'org.springframework.boot:spring-boot-starter-actuator'
Copy after login

2. Enabling Actuator Endpoints

By default, only a few endpoints are enabled. You can enable additional endpoints in your application.yml file:

management:
  endpoints:
    web:
      exposure:
        include: "*"  # This exposes all available endpoints
  endpoint:
    health:
      show-details: always  # Show detailed health information
Copy after login

Using Actuator Endpoints

Once Actuator is set up, you can access the various endpoints provided by it. Here are some commonly used endpoints:

1. Health Endpoint

The /actuator/health endpoint provides information about the health of your application:

GET http://localhost:8080/actuator/health
Copy after login

Example response:

{
  "status": "UP",
  "components": {
    "db": {
      "status": "UP",
      "details": {
        "database": "H2",
        "result": 1
      }
    },
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 499963174912,
        "free": 16989374464,
        "threshold": 10485760,
        "exists": true
      }
    }
  }
}
Copy after login

2. Metrics Endpoint

The /actuator/metrics endpoint provides various metrics related to your application:

GET http://localhost:8080/actuator/metrics
Copy after login

Example response:

{
  "names": [
    "jvm.memory.used",
    "jvm.gc.pause",
    "system.cpu.usage",
    "system.memory.usage",
    "http.server.requests"
  ]
}
Copy after login

To get details of a specific metric:

GET http://localhost:8080/actuator/metrics/jvm.memory.used
Copy after login

Example response:

{
  "name": "jvm.memory.used",
  "description": "The amount of used memory",
  "baseUnit": "bytes",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 5.1234567E7
    }
  ],
  "availableTags": [
    {
      "tag": "area",
      "values": [
        "heap",
        "nonheap"
      ]
    },
    {
      "tag": "id",
      "values": [
        "PS Eden Space",
        "PS Survivor Space",
        "PS Old Gen",
        "Metaspace",
        "Compressed Class Space"
      ]
    }
  ]
}
Copy after login

3. Environment Endpoint

The /actuator/env endpoint provides information about the environment properties:

GET http://localhost:8080/actuator/env
Copy after login

Example response:

{
  "activeProfiles": [],
  "propertySources": [
    {
      "name": "systemProperties",
      "properties": {
        "java.runtime.name": {
          "value": "Java(TM) SE Runtime Environment"
        },
        "java.vm.version": {
          "value": "25.181-b13"
        }
      }
    },
    {
      "name": "systemEnvironment",
      "properties": {
        "PATH": {
          "value": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        },
        "HOME": {
          "value": "/root"
        }
      }
    }
  ]
}
Copy after login

4. Info Endpoint

The /actuator/info endpoint provides information about the application:

GET http://localhost:8080/actuator/info
Copy after login

To customize the information, add properties in your application.yml:

info:
  app:
    name: My Spring Boot Application
    description: This is a sample Spring Boot application
    version: 1.0.0
Copy after login

Securing Actuator Endpoints

By default, all Actuator endpoints are accessible without authentication. To secure these endpoints, you can use Spring Security. Add the Spring Security dependency to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Copy after login

Update your application.yml to restrict access:

management:
  endpoints:
    web:
      exposure:
        include: "*"  # Expose all endpoints
  endpoint:
    health:
      show-details: always  # Show detailed health information

spring:
  security:
    user:
      name: admin  # Default username
      password: admin  # Default password

# Restrict actuator endpoints to authenticated users
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always
  security:
    enabled: true
    roles: ACTUATOR
Copy after login

Create a security configuration class to configure HTTP security:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/actuator/**").hasRole("ACTUATOR")
                .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}
Copy after login

With this configuration, only authenticated users with the ACTUATOR role can access the Actuator endpoints.

Customizing Actuator Endpoints

You can create custom Actuator endpoints to expose additional information or functionality specific to your application. Here’s an example of creating a custom endpoint:

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

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

    @ReadOperation
    public String customEndpoint() {
        return "Custom Actuator Endpoint";
    }
}
Copy after login

Access your custom endpoint at:

GET http://localhost:8080/actuator/custom
Copy after login

Conclusion

Spring Boot Actuator provides a robust set of tools to help you monitor and manage your application. By leveraging its built-in endpoints and the ability to create custom endpoints, you can gain valuable insights into your application’s performance and health. Secure these endpoints with Spring Security to ensure that only authorized users have access, and you’ll have a production-ready application that’s easy to manage and monitor.

Actuator is an essential part of any Spring Boot application, enabling you to keep your finger on the pulse of your application’s runtime environment and quickly respond to issues as they arise. Start using Spring Boot Actuator today to enhance your application’s observability and operational capabilities.

The above is the detailed content of A Beginners Guide to Using Spring Boot Actuator. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template