Home Java javaTutorial A Beginners Guide to Using Spring Boot Actuator

A Beginners Guide to Using Spring Boot Actuator

Aug 02, 2024 am 10:00 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles