当前位置: 首页 > news >正文

13.Spring boot中使用Actuator 监控

13.Spring boot中使用Actuator 监控

Spring Boot Actuator 是 Spring Boot 提供的一个强大的监控和管理工具,它通过暴露各种端点(Endpoints)来提供应用程序的运行时信息。这些端点可以帮助开发者和管理员监控应用程序的健康状况、性能指标、环境信息等。

在生产环境中,建议仅启用必要的端点,并启用安全限制以防止未经授权的访问。
敏感端点:某些端点(如 /actuator/env、/actuator/loggers)可能包含敏感信息,应谨慎处理。
建议结合 Spring Security 对 Actuator 端点进行访问控制。

  1. 快速集成 Spring Boot Actuator。
  2. 自定义健康检查和端点。

一、项目初始化

1. 项目结构
spring-boot-actuator-demo/
├── src/
│   ├── main/
│   │   ├── java/com/example/demo/
│   │   │   ├── DemoApplication.java          # 固定名称:主启动类
│   │   │   ├── actuator/                     # 自定义端点目录(非固定,可选)
│   │   │   │   └── CustomEndpoint.java       # 自定义端点类(非固定)
│   │   │   ├── health/                       # 自定义健康检查目录(非固定,可选)
│   │   │   │   └── CustomHealthIndicator.java # 自定义健康检查类(非固定)
│   │   │   └── config/                       # 配置类目录(非固定,可选)
│   │   │       └── SecurityConfig.java       # Spring Security 配置类(非固定)
│   │   └── resources/
│   │       ├── application.yml               # 固定名称:主配置文件
│   │       └── application-prod.yml          # 非固定名称:生产环境配置(可选)
└── pom.xml                                   # 固定名称:Maven 依赖管理

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>spring-boot-actuator-demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><!-- Spring Boot 父级依赖(固定名称,必须) --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.5</version> <!-- 使用最新稳定版本 --><relativePath/> <!-- 从仓库查找,不继承本地路径 --></parent><dependencies><!-- Spring Boot Web 依赖(非固定名称,按需添加) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Actuator 依赖(非固定名称,按需添加) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency></dependencies><!-- 构建配置(固定名称,通常无需修改) --><build><plugins><!-- Spring Boot Maven 插件(固定名称,必须) --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

创建主启动类 DemoApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

二、分步实现

第一步:基础 Actuator 集成(无需代码)

目标:仅通过配置文件启用 Actuator,并验证默认端点。

  1. 修改 pom.xml(固定名称)
    确保已添加 spring-boot-starter-actuator 依赖:

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  2. 配置 application.yml(固定名称)
    启用默认端点(如 healthinfo):

    server:port: 8080management:endpoints:web:exposure:include: "health,info"  # 仅暴露 health 和 info 端点
    
  3. 验证

    • 启动应用,访问:
      • http://localhost:8080/actuator/health(返回 {"status":"UP"}
      • http://localhost:8080/actuator/info(默认返回空对象 {}

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
暴露所有端点
在这里插入图片描述
在这里插入图片描述

第二步:自定义健康检查(需代码)

目标:添加一个自定义健康检查逻辑(例如检查外部服务状态)。

  1. 更新 application.yml(固定名称)
    配置健康检查显示详细信息:

    management:endpoint:health:show-details: always  # 显示健康检查的详细信息
    

    在这里插入图片描述
    在这里插入图片描述

  2. 创建 CustomHealthIndicator.java(非固定名称,但需遵循包路径)
    com.example.demo.health 包下创建类(包路径可自定义,但需与代码逻辑一致):

    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 {@Overridepublic Health health() {boolean isHealthy = checkExternalService(); // 模拟检查逻辑if (isHealthy) {return Health.up().withDetail("status", "External service is healthy,健康的").build();} else {return Health.down().withDetail("error", "External service is unavailable").build();}}private boolean checkExternalService() {// 实际场景中替换为真实检查逻辑(如 HTTP 请求、数据库连接等)return true; // 示例中始终返回 true}
    }
    

在这里插入图片描述

  1. 验证
    • 访问 http://localhost:8080/actuator/health,返回结果将包含自定义健康检查的详细信息。

在这里插入图片描述

第三步:自定义端点(需代码)

目标:添加一个自定义 Actuator 端点,支持 GET、POST 和 DELETE 操作。

  1. 创建 CustomEndpoint.java(非固定名称,但需遵循包路径)
    com.example.demo.actuator 包下创建类(包路径可自定义):

    import org.springframework.boot.actuate.endpoint.annotation.*;
    import org.springframework.stereotype.Component;
    import java.util.Collections;
    import java.util.Map;@Component
    @Endpoint(id = "custom")  // 端点 ID,访问路径为 /actuator/custom
    public class CustomEndpoint {// 只读端点(GET 请求)@ReadOperationpublic Map<String, String> customData() {return Collections.singletonMap("message", "Hello from Custom Actuator Endpoint!");}
    }
    

    在这里插入图片描述
    在这里插入图片描述

  2. 更新 application.yml(固定名称)
    暴露自定义端点:

    management:endpoints:web:exposure:include: "health,info,custom"  # 添加 custom 端点
    

在这里插入图片描述

  1. 验证
    • GET 请求:http://localhost:8080/actuator/custom
      返回 {"message":"Hello from Custom Actuator Endpoint!"}

在这里插入图片描述

三、核心配置文件说明

文件路径名称是否固定作用说明
pom.xml固定Maven 依赖管理文件,定义项目依赖。
application.yml固定主配置文件,定义 Actuator 端点暴露、安全配置等。
application-prod.yml非固定生产环境配置(可选),通过 spring.profiles.active=prod 激活。
CustomHealthIndicator.java非固定自定义健康检查逻辑,覆盖默认健康检查行为。
CustomEndpoint.java非固定自定义 Actuator 端点,支持 RESTful 操作(GET/POST/DELETE)。

四、生产环境建议

  1. 限制端点暴露
    仅暴露必要端点(如 health, info, metrics):
    management:endpoints:web:exposure:include: "health,info,metrics"
    

相关文章:

  • 链表的面试题3找出中间节点
  • git “分离头指针”(detached HEAD) 状态。
  • 【上位机——MFC】绘图
  • Servlet--快速入门及HTTP概述
  • DXFViewer进行中2 -> 直线 解析+渲染 ✅已完成
  • uniapp开发09-设置一个tabbar底部导航栏且配置icon图标
  • react-13react中外部css引入以及style内联样式(动态className与动态style)
  • 貌似我的ollama加载的模型被下载了两份?终于搞懂原理了。
  • 「Mac畅玩AIGC与多模态22」开发篇18 - 多段输出拼接与格式化展现工作流示例
  • ASP.NET Core 中间件
  • 微调大模型如何准备数据集——常用数据集,Alpaca和ShareGPT
  • PyTorch 与 TensorFlow 中基于自定义层的 DNN 实现对比
  • 基于Piecewise Jerk Speed Optimizer的速度规划算法(附ROS C++/Python仿真)
  • 免费视频压缩软件
  • 应用服务器Tomcat
  • 【优选算法 | 模拟】探索模拟算法: 编程与问题分析的双重 考验
  • SVG数据可视化设计(AI)完全工作流解读|计育韬
  • 如何使用 QuickAPI 推动汽车行业数据分享:数据仓库场景下的实践
  • 【开源深度解析】从零打造AI暗棋对战系统:Python实现中国象棋暗棋全攻略
  • 算法思想之深度优先搜索(DFS)、递归以及案例(最多能得到多少克黄金、精准核酸检测、最富裕的小家庭)
  • 预告:央行等部门将发声,介绍“一揽子金融政策支持稳市场稳预期”有关情况
  • “高校领域突出问题系统整治”已启动,聚焦招生、基建、师德等重点
  • 习近平对贵州毕节市黔西市游船倾覆事故作出重要指示
  • 福建两名厅级干部履新,张文胜已任省委省直机关工委副书记
  • 中国海警局新闻发言人就日民用飞机侵闯我钓鱼岛领空发表谈话
  • 英国传统两党受挫地方选举后反思,改革党异军突起“突破想象”