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

前言

🤟 找工作,来万码优才:👉 #小程序://万码优才/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 配合使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值