跳到主要内容

Actuator 监控

问题

Spring Boot Actuator 是什么?如何实现应用的健康检查和监控?

答案

Actuator 概述

Spring Boot Actuator 提供生产级的应用监控和管理功能,通过 HTTP 端点或 JMX 暴露应用内部信息。

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

常用端点

端点路径功能
health/actuator/health健康检查(数据库、Redis、磁盘等)
info/actuator/info应用信息(版本、Git 信息)
metrics/actuator/metrics应用指标(JVM、HTTP、线程池)
env/actuator/env环境变量和配置属性
beans/actuator/beans所有注册的 Bean
mappings/actuator/mappings所有 @RequestMapping 路由
loggers/actuator/loggers查看/修改日志级别
threaddump/actuator/threaddump线程转储
heapdump/actuator/heapdump堆转储文件下载
shutdown/actuator/shutdown优雅停机(默认禁用)

端点配置

application.yml
management:
endpoints:
web:
exposure:
# 暴露哪些端点(默认只暴露 health)
include: health,info,metrics,prometheus
# 排除敏感端点
exclude: env,beans
base-path: /actuator # 端点前缀(默认)

endpoint:
health:
show-details: when-authorized # 健康详情展示策略
# always:始终显示 / when-authorized:认证后显示 / never:隐藏
shutdown:
enabled: false # 不启用 shutdown 端点

# 安全:建议使用不同端口暴露管理端点
server:
port: 9090 # 管理端点使用独立端口
安全注意

生产环境中 Actuator 端点包含敏感信息(环境变量、堆转储等),务必:

  1. 限制暴露的端点(只开放 health、prometheus)
  2. 使用独立端口或 Spring Security 保护
  3. 不要暴露 env、heapdump 到公网

自定义健康检查

CustomHealthIndicator.java
@Component
public class ExternalApiHealthIndicator implements HealthIndicator {

private final RestTemplate restTemplate;

public ExternalApiHealthIndicator(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

@Override
public Health health() {
try {
ResponseEntity<String> response = restTemplate
.getForEntity("https://api.example.com/health", String.class);
if (response.getStatusCode().is2xxSuccessful()) {
return Health.up()
.withDetail("api", "reachable")
.withDetail("responseTime", "50ms")
.build();
}
return Health.down()
.withDetail("api", "unhealthy")
.withDetail("status", response.getStatusCode())
.build();
} catch (Exception e) {
return Health.down(e)
.withDetail("api", "unreachable")
.build();
}
}
}

健康检查响应示例:

GET /actuator/health
{
"status": "UP",
"components": {
"db": { "status": "UP", "details": { "database": "MySQL" } },
"redis": { "status": "UP" },
"externalApi": { "status": "UP", "details": { "api": "reachable" } },
"diskSpace": { "status": "UP", "details": { "free": "50GB" } }
}
}

自定义 Metrics 指标

自定义指标
@Service
public class OrderService {

private final Counter orderCounter;
private final Timer orderTimer;

public OrderService(MeterRegistry registry) {
// 计数器:订单总数
this.orderCounter = Counter.builder("orders.created.total")
.description("Total orders created")
.tag("type", "all")
.register(registry);

// 计时器:订单处理耗时
this.orderTimer = Timer.builder("orders.process.duration")
.description("Order processing duration")
.register(registry);
}

public Order createOrder(OrderDTO dto) {
return orderTimer.record(() -> {
// 业务逻辑...
Order order = processOrder(dto);
orderCounter.increment();
return order;
});
}
}

集成 Prometheus + Grafana

application.yml
management:
endpoints:
web:
exposure:
include: health,prometheus
metrics:
export:
prometheus:
enabled: true
tags:
application: my-app # 全局标签
pom.xml
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

常见面试问题

Q1: Spring Boot Actuator 的作用?

答案

Actuator 提供生产级的监控和管理功能。通过 HTTP 端点暴露应用健康状态(health)、运行指标(metrics)、环境配置(env)、日志管理(loggers)等信息。常见应用:健康检查(K8s 存活/就绪探针)、指标监控(集成 Prometheus + Grafana)、运行时日志级别调整

Q2: 如何在 K8s 中使用 Actuator 做健康检查?

答案

K8s Pod 配置
livenessProbe:        # 存活探针
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
readinessProbe: # 就绪探针
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10

Spring Boot 2.3+ 内置了 liveness 和 readiness 健康组,可以分别检测应用是否存活和是否准备好接收请求。

Q3: 如何保护 Actuator 端点的安全?

答案

  1. 限制暴露端点:只开放必要的端点(health、prometheus)
  2. 独立端口:管理端点使用不同端口(management.server.port
  3. Spring Security:对敏感端点添加认证
  4. 网络隔离:管理端口只在内网可访问

Q4: Micrometer 是什么?

答案

Micrometer 是 Spring Boot 2.x 引入的指标门面,类似于日志领域的 SLF4J。它提供统一的指标 API(Counter、Timer、Gauge 等),可以对接多种监控系统(Prometheus、Datadog、InfluxDB 等),切换监控后端只需更换依赖,不需要修改代码。

相关链接