项目监测

Spring Boot Actuator 项目监测详解:从配置到实战应用

Spring Boot Actuator 是 Spring Boot 提供的项目监测与管理组件,通过暴露一系列端点(Endpoint),帮助开发者实时监控应用的健康状态、配置信息、性能指标等。本文基于 Spring Boot 2.x 版本,从 “依赖配置→核心端点→安全控制→自定义扩展” 四个维度,详细讲解 Actuator 的使用方法,帮你全面掌握项目监测能力。

Actuator 核心价值与基础配置

1. 核心价值

  • 实时监控:无需手动开发,通过端点直接获取应用健康状态、配置信息、线程快照等;
  • 性能分析:提供 metrics 端点,记录 JVM 内存、GC 次数、请求耗时等关键指标;
  • 运维支持:支持动态调整日志级别、刷新配置等操作,简化运维流程;
  • 可扩展性:允许自定义健康检查、信息展示等,适配业务监控需求。

2. 基础依赖配置

pom.xml 中添加 Actuator 依赖(Spring Boot 2.x 版本):

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

注意

  • 若需通过 HTTP 访问端点(最常用方式),需确保已添加 spring-boot-starter-web 依赖;
  • 依赖引入后,Actuator 会自动生效,默认暴露 /actuator/health/actuator/info 两个端点。

端点(Endpoint)详解:分类与核心功能

Actuator 提供的端点按功能可分为监测类配置类操作类,Spring Boot 2.x 中默认仅暴露少量端点,需通过配置手动开启其他端点。

1. 端点访问规则

  • 默认访问路径:http://{ip}:{port}/actuator/{endpoint}(如 http://localhost:8080/actuator/health);
  • 可自定义根路径:通过 management.endpoints.web.base-path 修改(如改为 /monitor,则访问路径为 http://localhost:8080/monitor/health);
  • 端点状态:部分端点为 “只读”(如 healthbeans),部分支持 “写操作”(如 loggers 可动态修改日志级别)。

2. 核心端点功能说明

端点名称 功能描述 常用场景 访问方式
/health 应用健康检查状态 监控应用存活状态(UP/DOWN) GET
/info 应用自定义信息(如版本、作者) 展示应用元数据(如部署版本) GET
/beans 列出 Spring 容器中所有 Bean 的信息 排查 Bean 注册问题(是否单例、依赖关系) GET
/env 显示应用所有配置环境(系统变量、配置文件) 检查配置是否生效(如数据库连接参数) GET
/metrics 应用度量指标(JVM、请求、缓存等) 分析性能瓶颈(如内存占用、请求 QPS) GET
/threaddump 线程快照(状态、堆栈信息) 排查线程阻塞、死锁问题 GET
/heapdump JVM 堆内存快照(HProf 格式) 分析内存泄漏问题 GET
/mappings 所有 URL 映射关系(控制器接口、Servlet) 检查接口路径是否正确配置 GET
/scheduledtasks 定时任务列表 确认定时任务是否注册、执行周期是否正确 GET
/loggers 日志级别配置 动态调整日志级别(无需重启应用) GET/POST
/refresh 刷新配置(配合 Spring Cloud Config 使用) 动态加载最新配置(如数据库连接参数修改) POST

3. 端点暴露配置

Spring Boot 2.x 中,端点默认仅暴露 healthinfo,需通过配置指定暴露的端点:

(1)暴露所有端点(开发环境)
management:
  endpoints:
    web:
      exposure:
        include: '*'  # 暴露所有端点(生产环境不推荐)
        # exclude: env,threaddump  # 排除敏感端点
(2)暴露指定端点(生产环境推荐)
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,health  # 仅暴露必要端点
  endpoint:
    health:
      show-details: when_authorized  # 健康详情仅授权用户可见
    metrics:
      enabled: true  # 启用 metrics 端点
(3)自定义端点根路径
management:
  endpoints:
    web:
      base-path: /monitor  # 根路径改为 /monitor,访问地址变为 http://localhost:8080/monitor/health

关键端点实战:从监控到问题排查

1. /health 端点:健康检查

/health 是最常用的端点,用于监控应用及依赖组件(数据库、Redis 等)的健康状态。

(1)默认输出(简洁模式)
{
  "status": "UP"  // UP:健康;DOWN:不健康;OUT_OF_SERVICE:不可用;UNKNOWN:未知
}
(2)显示详情(需配置)
management:
  endpoint:
    health:
      show-details: always  # always:总是显示;when_authorized:仅授权用户;never:不显示

配置后输出示例(包含数据库、Redis 等组件的健康状态):

{
  "status": "UP",
  "components": {
    "db": {  // 数据库健康状态
      "status": "UP",
      "details": {
        "database": "MySQL",
        "validationQuery": "SELECT 1"
      }
    },
    "redis": {  // Redis 健康状态
      "status": "UP",
      "details": {
        "version": "6.2.6"
      }
    },
    "diskSpace": {  // 磁盘空间健康状态
      "status": "UP",
      "details": {
        "total": 107374182400,
        "free": 53687091200,
        "threshold": 10485760
      }
    }
  }
}
(3)自定义健康检查

若需监控业务组件(如第三方 API 连接状态),可实现 HealthIndicator 接口:

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

// 自定义健康检查器(监控第三方支付 API 状态)
@Component
public class PaymentApiHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // 模拟检查第三方 API 连接
        boolean isAlive = checkPaymentApiAlive();
        
        if (isAlive) {
            // 健康状态:UP,附加详情
            return Health.up()
                    .withDetail("message", "支付 API 连接正常")
                    .withDetail("responseTime", "200ms")
                    .build();
        } else {
            // 健康状态:DOWN,附加错误信息
            return Health.down()
                    .withDetail("message", "支付 API 连接超时")
                    .withDetail("error", "Connection timed out")
                    .build();
        }
    }

    // 检查第三方 API 是否存活
    private boolean checkPaymentApiAlive() {
        // 实际项目中:发送 HTTP 请求检查 API 响应
        return true; // 模拟健康
    }
}

配置后,/health 端点会新增 paymentApi 组件的健康状态:

{
  "status": "UP",
  "components": {
    "paymentApi": {
      "status": "UP",
      "details": {
        "message": "支付 API 连接正常",
        "responseTime": "200ms"
      }
    },
    // 其他组件...
  }
}

2. /info 端点:自定义应用信息

/info 端点用于展示应用元数据(如版本、作者、Git 信息等),需通过配置或代码自定义。

(1)配置文件定义信息
# application.yml
info:
  app:
    name: "用户服务"
    version: "1.0.0"
    author: "张三"
  git:
    commit:
      id: "a1b2c3d"  # 可通过 Git 插件自动填充

访问 /actuator/info 输出:

{
  "app": {
    "name": "用户服务",
    "version": "1.0.0",
    "author": "张三"
  },
  "git": {
    "commit": {
      "id": "a1b2c3d"
    }
  }
}
(2)代码自定义信息(实现 InfoContributor)
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomInfoContributor implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        // 动态添加信息(如当前在线用户数)
        Map<String, Object> stats = new HashMap<>();
        stats.put("onlineUsers", 156);  // 模拟在线用户数
        stats.put("totalRequests", 12500);  // 模拟总请求数
        
        builder.withDetail("stats", stats);
    }
}

访问 /actuator/info 会新增 stats 节点:

{
  "app": { ... },
  "git": { ... },
  "stats": {
    "onlineUsers": 156,
    "totalRequests": 12500
  }
}

3. /metrics 端点:性能指标监控

/metrics 端点提供应用运行时的关键指标(JVM 内存、GC、请求耗时等),帮助分析性能瓶颈。

(1)查看所有可用指标

访问 /actuator/metrics 会返回指标名称列表:

{
  "names": [
    "jvm.memory.used",          // JVM 已使用内存
    "jvm.gc.memory.promoted",   // GC 晋升内存
    "http.server.requests",     // HTTP 请求指标
    "system.cpu.usage",         // CPU 使用率
    "disk.free"                 // 磁盘空闲空间
  ]
}
(2)查看具体指标详情

访问 /actuator/metrics/{指标名称}(如 /actuator/metrics/jvm.memory.used):

{
  "name": "jvm.memory.used",
  "description": "The amount of used memory",
  "baseUnit": "bytes",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 256453632  // 当前值:约 256MB
    }
  ],
  "availableTags": [
    {
      "tag": "area",
      "values": ["heap", "nonheap"]  // 可按堆/非堆筛选
    },
    {
      "tag": "id",
      "values": ["Eden Space", "Survivor Space", "Metaspace"]
    }
  ]
}
(3)按标签筛选指标

通过 tag 参数筛选(如查看堆内存使用):

/actuator/metrics/jvm.memory.used?tag=area:heap

4. /loggers 端点:动态调整日志级别

无需重启应用,通过 /loggers 端点动态修改指定类的日志级别(开发 / 生产环境均实用)。

(1)查看当前日志级别配置

访问 /actuator/loggers/com.example.demo(指定包路径):

{
  "configuredLevel": "INFO",  // 当前配置的日志级别
  "effectiveLevel": "INFO"    // 实际生效的日志级别
}
(2)动态修改日志级别(POST 请求)

发送 POST 请求到 /actuator/loggers/com.example.demo,请求体为:

{
  "configuredLevel": "DEBUG"  // 修改为 DEBUG 级别
}

修改后,该包下的类会输出 DEBUG 级别的日志,便于临时排查问题。

5. /threaddump/heapdump:问题排查利器

  • /threaddump:获取线程快照,包含线程状态、堆栈信息,用于排查线程阻塞、死锁问题;
  • /heapdump:下载 JVM 堆内存快照(.hprof 文件),可用 MAT 等工具分析内存泄漏。

安全控制:保护敏感端点

Actuator 端点包含大量敏感信息(如 /env 暴露配置、/threaddump 暴露代码堆栈),生产环境必须通过安全框架(如 Spring Security)限制访问。

1. 集成 Spring Security 控制访问

(1)添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
(2)配置安全规则
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 ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 仅允许认证用户访问 Actuator 端点
            .requestMatchers().antMatchers("/actuator/**")
            .and()
            .authorizeRequests()
            .anyRequest().hasRole("ACTUATOR_ADMIN")  // 需具有 ACTUATOR_ADMIN 角色
            .and()
            .httpBasic();  // 使用 HTTP 基本认证
    }
}
(3)配置用户与角色
spring:
  security:
    user:
      name: admin  # 用户名
      password: 123456  # 密码(生产环境需加密)
      roles: ACTUATOR_ADMIN  # 分配角色

配置后,访问 Actuator 端点需输入用户名 / 密码,且仅 admin 可访问。

自定义端点(进阶)

除了内置端点,Actuator 支持自定义端点,用于暴露业务监控指标(如订单量、支付成功率)。

1. 自定义端点示例(Spring Boot 2.x 注解方式)

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

// 自定义端点:/actuator/order-stats
@Endpoint(id = "order-stats")
@Component
public class OrderStatsEndpoint {

    // 模拟订单统计数据
    private Map<String, Object> getOrderStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("todayOrders", 1250);  // 今日订单数
        stats.put("successRate", 99.2);  // 支付成功率
        stats.put("avgAmount", 235.5);   // 平均订单金额
        return stats;
    }

    // 只读操作(GET 请求)
    @ReadOperation
    public Map<String, Object> getStats() {
        return getOrderStats();
    }
}

2. 暴露自定义端点

management:
  endpoints:
    web:
      exposure:
        include: order-stats,health,info  # 包含自定义端点

访问 /actuator/order-stats 输出:

{
  "todayOrders": 1250,
  "successRate": 99.2,
  "avgAmount": 235.5
}

生产环境最佳实践

  1. 最小化暴露端点:仅暴露必要端点(如 healthinfometrics),禁用敏感端点(envthreaddump);
  2. 强制安全认证:通过 Spring Security 控制访问,使用 HTTPS 加密传输;
  3. 限制健康详情可见性:配置 management.endpoint.health.show-details: when_authorized,仅授权用户查看详情;
  4. 结合监控系统:将 Actuator 与 Prometheus + Grafana 集成,实现指标可视化与告警;
  5. 定期清理堆快照/heapdump 生成的文件较大,避免频繁调用,或配置自动清理。

总结

Spring Boot Actuator 是项目监测的 “瑞士军刀”,通过简单配置即可获取应用健康状态、性能指标、配置信息等关键数据:

  1. 基础配置:添加 spring-boot-starter-actuator 依赖,配置端点暴露规则;
  2. 核心端点health 监控健康、info 展示元数据、metrics 分析性能、loggers 动态调整日志;
  3. 安全控制:集成 Spring Security 保护敏感端点,避免信息泄露;
  4. 自定义扩展:通过 @Endpoint 实现业务监控端点,满足个性化需求