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

Spring Boot Actuator 自定义健康检查(附Demo)

目录

  • 前言
  • 1. Demo
  • 2. 拓展

前言

🤟 找工作,来万码优才:👉 #小程序://万码优才/r6rqmzDaXpYkJZF

Spring Boot 的 actuator 提供了应用监控的功能,其中健康检查(Health Check)是一个重要的部分,可以自定义健康检查,并且可以单独设置 Actuator 端口

1. Demo

实战中的Demo可用于如下:

  • 检测某个外部服务是否可用
  • 监测某个业务逻辑的状态

如果是 Maven 项目,需在 pom.xml 中添加:

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

启用 Actuator 端点

在 application.yml 配置文件中:

management:
  endpoints:
    web:
      exposure:
        include: health # 只暴露健康检查端点
  health:
    show-details: always # 显示详细健康信息

或者是在application/properties:

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

自定义健康检查,自定义 HealthIndicator 需要实现 org.springframework.boot.actuate.health.HealthIndicator 接口,覆盖 health() 方法:

  • Health.up():表示服务状态正常
  • Health.down():表示服务状态异常
  • withDetail():添加额外的诊断信息
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() {
        // 模拟检查逻辑(比如检查某个服务是否可用)
        boolean serviceRunning = checkServiceStatus();
        
        if (serviceRunning) {
            return Health.up()
                    .withDetail("service", "Running")
                    .build();
        } else {
            return Health.down()
                    .withDetail("service", "Down")
                    .withDetail("reason", "Service Unreachable")
                    .build();
        }
    }

    private boolean checkServiceStatus() {
        // 模拟服务状态检查
        return Math.random() > 0.5;
    }
}

后续增加一个启动类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @description: 自动装配知识点
 * @Author lxs
 * @Date 2025/3/17 14:26
 */
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

总体截图如下:

在这里插入图片描述

访问如下:http://127.0.0.1:8080/actuator/health,0.5的概率随机

在这里插入图片描述

基本的知识如下:
status: UP 表示应用状态正常
customHealthIndicator 是我们自定义的健康检查
diskSpace 表示磁盘健康情况

也可配置不一样的端口号
在 application.yml 中:

server:
  port: 8080  # 主应用端口

management:
  server:
    port: 9000  # Actuator 端口
  endpoints:
    web:
      exposure:
        include: "*"  # 暴露所有 Actuator 端点
  1. 访问 Actuator 端点
    应用运行后:
    http://localhost:8080/ 访问主应用
    http://localhost:9000/actuator/health 访问健康检查

2. 拓展

常见的 Actuator 端点

端点说明访问地址
/actuator查看所有可用端点http://localhost:9000/actuator
/actuator/health查看应用健康状态http://localhost:9000/actuator/health
/actuator/info查看应用信息http://localhost:9000/actuator/info
/actuator/metrics查看应用指标http://localhost:9000/actuator/metrics
/actuator/metrics/{name}查看具体指标(如 jvm.memory.used)http://localhost:9000/actuator/metrics/jvm.memory.used
/actuator/mappings查看所有 Spring MVC 映射http://localhost:9000/actuator/mappings
/actuator/loggers查看和修改日志级别http://localhost:9000/actuator/loggers
/actuator/env查看环境变量http://localhost:9000/actuator/env
/actuator/beans查看 Spring Bean 信息http://localhost:9000/actuator/beans
/actuator/threaddump线程 Dump 信息http://localhost:9000/actuator/threaddump
/actuator/shutdown关闭应用(默认禁用)http://localhost:9000/actuator/shutdown
  1. 只暴露部分端点
management:
  endpoints:
    web:
      exposure:
        include: "health,info,metrics"

访问 http://localhost:9000/actuator:

{
  "_links": {
    "self": { "href": "http://localhost:9000/actuator", "templated": false },
    "health": { "href": "http://localhost:9000/actuator/health", "templated": false },
    "info": { "href": "http://localhost:9000/actuator/info", "templated": false },
    "metrics": { "href": "http://localhost:9000/actuator/metrics", "templated": false }
  }
}
  1. 关闭特定端点
management:
  endpoint:
    shutdown:
      enabled: false  # 禁用 shutdown 端点,防止误操作
    health:
      enabled: true  # 启用健康检查

访问 http://localhost:9000/actuator/shutdown:

{
  "error": "Not Found",
  "status": 404
}
  1. 配置 metrics 指标
    jvm.memory.used 监测 JVM 内存占用
    system.cpu.usage 监测 CPU 使用率
management:
  metrics:
    export:
      prometheus:
        enabled: true  # 启用 Prometheus 监控

访问 http://localhost:9000/actuator/metrics

{
  "names": [
    "jvm.memory.used",
    "jvm.memory.max",
    "http.server.requests",
    "system.cpu.usage"
  ]
}

访问 http://localhost:9000/actuator/metrics/jvm.memory.used

{
  "name": "jvm.memory.used",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 25000000
    }
  ],
  "availableTags": [
    {
      "tag": "area",
      "values": ["heap", "nonheap"]
    }
  ]
}

可以暴露 Prometheus 监控数据,方便与 Grafana 配合使用

相关文章:

  • AI安全、大模型安全研究(DeepSeek)
  • 3. 轴指令(omron 机器自动化控制器)——>MC_SetPosition
  • Python(数据结构概念,算法时间效率衡量,链表)
  • Oracle GoldenGate (OGG) 安装、使用及常见故障处理
  • 英伟达黄仁勋2025GTC演讲深度解析:液冷GPU、AI工厂、机器人AI…...
  • 【NoC仿真器(nirgam noxim)搭建】自用笔记
  • Debian 12系统中允许Root远程SSH登录解决方法!
  • python 数据可视化TVTK库安装与使用
  • RabbitMQ 集群搭建步驟
  • TG电报群管理机器人定制开发的重要性
  • C语言问题总结(二)
  • 数据分析的12个挑战及其解决方法
  • Event driven agentic document workflows 笔记 - 1
  • 开源软件许可证冲突的原因和解决方法
  • 【Linux】VMware Workstation Pro 17 安装教程
  • 【实战案例】用STAR+3W模型拆解电商支付系统设计文档
  • 移动端医疗AI诊断系统的设计思路与技术展望——多模态生理数据分析的理论框架探讨
  • 中小企业如何低成本构建高效专属网络?
  • 快速入手-基于Django的mysql配置(三)
  • 分布式中间件:RabbitMQ死信队列和延迟队列
  • 广西百色通报:极端强对流天气致墙体倒塌,3人遇难7人受伤
  • 国际足联女子世界杯再次扩军,2031年起增至48支球队
  • 经济日报刊文:品牌经营不能让情怀唱“独角戏”
  • 三星“七天机”质保期内屏幕漏液被要求自费维修,商家:系人为损坏
  • 国家出口管制工作协调机制办公室部署开展打击战略矿产走私出口专项行动
  • 晋级中部非省会第一城,宜昌凭什么