学技术学英文:SpringBoot的内置监控组件-Spring Boot Actuator

news/2024/12/22 14:30:49 标签: spring boot, 后端, java, 监控, actuator

导读:

Spring Boot Actuator是Spring Boot提供的一个模块,简单配置后就能开启,属于拿来即用,具体功能如下:

监控和管理Spring Boot应用

Spring Boot Actuator提供了一组REST端点和命令行工具,用于查看应用的运行状态、性能指标和健康状况等。通过这些端点,开发人员可以方便地获取应用的各类信息,如:健康检查、度量和指标、环境信息

应用度量数据的导出

Spring Boot Actuator支持将应用的运行数据导出到各种不同的存储后端,例如Prometheus、Datadog、New Relic等。这样,开发人员可以方便地使用这些数据来进一步分析和监控应用的性能和健康状况。

自定义端点和安全控制

发人员可以根据自己的需求来暴露自定义的监控数据,为了安全还支持限制访问权限、身份验证

其他工具的集成

Spring Boot Actuator可以与多种外部监控工具集成,如Prometheus和Grafana,进行更高级别的应用监控和管理。通过添加Micrometer和Prometheus依赖,可以将Actuator的指标数据导出到Prometheus,并使用Grafana进行可视化展示。

Introduction

Spring Boot Actuator is a sub-project of Spring Boot that provides a set of built-in production-ready features to help you monitor and manage your application. Actuator includes several endpoints that allow you to interact with the application, gather metrics, check the health, and perform various management tasks.

In this article, we will delve into the features of Spring Boot Actuator, how to set it up, and provide examples to demonstrate its capabilities.

Setting Up Spring Boot Actuator

To get started with Spring Boot Actuator, you need to add the `spring-boot-starter-actuator` dependency to your project. If you’re using Maven, add the following to your `pom.xml` file:

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

For Gradle, add the following line to your `build.gradle` file:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

Configuring Actuator Endpoints

By default, Actuator endpoints are exposed over HTTP. You can configure which endpoints are enabled and how they are accessed in your `application.properties` or `application.yml` file.

Here’s an example configuration in `application.properties`:

management.endpoints.web.exposure.include=health,info
management.endpoint.health.show-details=always

In `application.yml`:

management:
  endpoints:
    web:
      exposure:
        include: health, info
  endpoint:
    health:
      show-details: always

Common Actuator Endpoints

Spring Boot Actuator provides a variety of built-in endpoints. Below are some of the most commonly used ones:

/actuator/health: Displays the health status of the application.
/actuator/info: Displays arbitrary application information.
/actuator/metrics: Shows ‘metrics’ information for the current application.
/actuator/env: Displays properties from the `Environment`.
/actuator/beans: Displays a complete list of all Spring beans in your application.

Example: Health Endpoint

The health endpoint provides basic information about the application’s health. To access it, navigate to `/actuator/health` in your browser or use a tool like `curl`:

curl http://localhost:8080/actuator/health

The response will look something like this:

{
 "status": "UP"
}

You can add custom health indicators to include more detailed information. For example:

java">import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // Custom health check logic
        boolean isHealthy = checkCustomHealth();
        if (isHealthy) {
            return Health.up().withDetail("CustomHealth", "All systems are operational").build();
        } else {
            return Health.down().withDetail("CustomHealth", "Some systems are down").build();
        }
    }

    private boolean checkCustomHealth() {
        // Implement your custom health check logic
        return true;
    }
}

Metrics and Monitoring

The `/actuator/metrics` endpoint provides various application metrics. For example, to see JVM memory usage, you can query:

curl http://localhost:8080/actuator/metrics/jvm.memory.used

The response will look like this:

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

Customizing Actuator Endpoints

You can create custom endpoints by implementing the `Endpoint` interface. Here’s an example of a custom endpoint that returns a simple message:

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

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

    @ReadOperation
    public String customEndpoint() {
        return "This is a custom endpoint";
    }
}

This endpoint can be accessed at `/actuator/custom`.

Securing Actuator Endpoints

By default, all Actuator endpoints are unsecured. In a production environment, it is crucial to secure them. You can do this using Spring Security. First, add the Spring Security dependency:

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

Then, configure security in your `application.properties`:

management.endpoints.web.exposure.include=health,info
management.endpoint.health.show-details=always
management.endpoints.web.base-path=/actuator

And create a security configuration class:

java">import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

This configuration requires authentication for all Actuator endpoints and uses basic authentication.

Conclusion

Spring Boot Actuator is a powerful tool for monitoring and managing your application. It provides numerous built-in endpoints to check the application’s health, gather metrics, and perform various management tasks. By understanding how to configure and use these endpoints, you can ensure your application runs smoothly and efficiently.

By integrating custom health indicators, custom endpoints, and securing these endpoints using Spring Security, you can tailor Actuator to meet your specific needs. Whether you’re in development or production, Spring Boot Actuator is an invaluable component of the Spring Boot ecosystem.


http://www.niftyadmin.cn/n/5795451.html

相关文章

【CAN总线】STM32的CAN外设

目录 CAN外设CAN网络拓扑结构TJA1050芯片手册的应用电路CAN框图 CAN外设 在STM32F10xx参考手册第22章 控制器局域网 bxCAN • STM32内置bxCAN外设&#xff08;CAN控制器&#xff09;&#xff0c;支持CAN2.0A和2.0B&#xff0c;可以自动发送CAN报文和按照过滤器自动接收指定CA…

CCF-GESP 等级考试 2023年3月认证C++二级真题解析

2023年3月真题 一、单选题&#xff08;每题2分&#xff0c;共30分&#xff09; 正确答案&#xff1a;D 解析&#xff1a;考察知识点&#xff1a;计算机的存储 光盘是光存储介质&#xff0c;是通过激光高温改变光盘涂覆层的形状来记录数据的&#xff0c;不会因为磁场而改变记录…

centos7下制作DockerFile 镜像

文章目录 介绍DockerFile 常用命令示例1.创建Dockerfile文件2.构建Dockerfile镜像3.验证结果 小结 介绍 Dockerfile 是一个文本文件&#xff0c;包含了用于构建 Docker 镜像的所有命令和指令。它定义了镜像的构建过程&#xff0c;包括基础镜像、安装软件、设置环境变量、复制文…

Java web的发展历史

目录 前言&#xff1a; 一.Model I和Model II 1.Model I开发模式 ​编辑 2.Model II开发模式 二. MVC模式 前言&#xff1a; 该篇文章主要介绍了Java web的发展历史&#xff0c;以及MVC相关内容 一.Model I和Model II 1.Model I开发模式 Model1的开发模式是&#xff…

【JavaEE初阶】线程安全问题

本节⽬标 掌握什么是线程不安全及解决思路掌握 synchronized、volatile 关键字 一、多线程带来的的⻛险-线程安全 (重点) 1 观察线程不安全 package Thread.ThreadUnsecurity;public class Unsecurity {public static int count0;public static void main(String[] args) t…

Linux中部署项目

1.下载JDK17 进入 /usr/local 目录&#xff0c;创建 java 文件夹。并将 JDK17 上传到 java 目录下。 上传成功后&#xff0c;通过cd命令进入Java文件夹目录&#xff0c;解压 JDK17 压缩包&#xff0c;命令 unzip zulu17.44.53-ca-jdk17.0.8.1-linux_x64.zip。 如果报错说 u…

详解 Qt WebEngine 模块

Qt WebEngine 模块是 Qt 提供的一个功能强大的模块&#xff0c;用于在 Qt 应用中嵌入和显示现代网页内容。该模块基于 Chromium 引擎&#xff0c;支持丰富的 Web 技术&#xff08;如 HTML5、CSS3、JavaScript 等&#xff09;&#xff0c;适合需要嵌入网页浏览、Web 应用、JavaS…

在 .NET 5.0 运行 .NET 8.0 教程:使用 ASP.NET Core 创建 Web API

前言 因为我本机安装的是vs2019&#xff0c;所以我在使用vs创建项目的时候&#xff0c;只能选择.NET 5.0&#xff0c;而无法选择.NET 8.0 在网上有看到说用vs2019使用.net 8.0 &#xff0c;但是感觉不可靠&#xff0c;要用还是安装vs2022吧。 我因为不想要安装vs2022。 但是微…