Spring Boot Actuator健康检查与生产级监控配置指南

Spring Boot Actuator提供生产级应用监控端点,包含健康检查、指标采集、环境信息、日志级别动态调整等功能。在微服务架构中,Actuator端点是Kubernetes探针、负载均衡健康检测和APM系统数据采集的基础。默认配置存在安全风险,需根据生产环境需求做精细化权限控制和信息暴露管理。

Actuator引入与端点配置

添加Actuator依赖后即可使用内置监控端点,无需额外代码:

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

<!-- Micrometer Prometheus集成 -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<!-- Gradle -->
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-registry-prometheus'

application.yml配置端点暴露策略:

management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus,metrics,env,loggers,threaddump
        exclude: shutdown,heapdump
      base-path: /actuator
  endpoint:
    health:
      show-details: when_authorized
      show-components: when_authorized
      probes:
        enabled: true
    prometheus:
      enabled: true
    metrics:
      tags:
        application: ${spring.application.name}
        instance: ${HOSTNAME:unknown}
  metrics:
    distribution:
      percentiles-histogram:
        http.server.requests: true
      percentiles:
        http.server.requests: 0.5,0.95,0.99
    tags:
      common:
        environment: ${spring.profiles.active:default}

自定义健康检查指标

默认健康端点检查数据库连接和磁盘空间。业务系统需要扩展自定义检查项,如外部API可达性、消息队列连接、缓存命中率等。

@Component
public class DatabaseHealthIndicator implements HealthIndicator {

    private final DataSource dataSource;

    public DatabaseHealthIndicator(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Health health() {
        try (Connection conn = dataSource.getConnection();
             Statement stmt = conn.createStatement()) {

            stmt.execute("SELECT 1");

            HikariPoolMXBean pool = ((HikariDataSource) dataSource)
                .getHikariPoolMXBean();

            Map<String, Object> details = new HashMap<>();
            details.put("active", pool.getActiveConnections());
            details.put("idle", pool.getIdleConnections());
            details.put("total", pool.getTotalConnections());
            details.put("threadsAwaiting", pool.getThreadsAwaitingConnection());

            if (pool.getActiveConnections() > pool.getTotalConnections() * 0.8) {
                return Health.status("DEGRADED").withDetails(details).build();
            }

            return Health.up().withDetails(details).build();

        } catch (Exception e) {
            return Health.down()
                .withDetail("error", e.getMessage())
                .withDetail("timestamp", System.currentTimeMillis())
                .build();
        }
    }
}

@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.exchange(
                "https://api.payment.example.com/health",
                HttpMethod.GET, null, String.class
            );

            if (response.getStatusCode().is2xxSuccessful()) {
                return Health.up()
                    .withDetail("statusCode", response.getStatusCodeValue())
                    .build();
            }

            return Health.down()
                .withDetail("statusCode", response.getStatusCodeValue())
                .build();

        } catch (Exception e) {
            return Health.down()
                .withDetail("error", "Payment API unreachable: " + e.getMessage())
                .build();
        }
    }
}

健康端点返回嵌套结构,每个Indicator独立报告:

// GET /actuator/health
{
  "status": "UP",
  "components": {
    "db": {
      "status": "UP",
      "details": { "database": "MySQL", "active": 5, "idle": 10 }
    },
    "externalApi": {
      "status": "DEGRADED",
      "details": { "statusCode": 503 }
    },
    "diskSpace": {
      "status": "UP",
      "details": { "total": 107374182400, "free": 53687091200 }
    }
  }
}

Kubernetes探针集成

Actuator的probes端点直接对接K8s存活探针和就绪探针。存活探针失败会触发容器重启,就绪探针失败会将Pod从Service Endpoints移除。

management:
  endpoint:
    health:
      probes:
        enabled: true
      groups:
        liveness:
          include: livenessState
        readiness:
          include: readinessState,db,externalApi

K8s Deployment配置探针:

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: app
        image: app:latest
        livenessProbe:
          httpGet:
            path: /actuator/health/liveness
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /actuator/health/readiness
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 5
          failureThreshold: 3
        startupProbe:
          httpGet:
            path: /actuator/health
            port: 8080
          initialDelaySeconds: 0
          periodSeconds: 5
          failureThreshold: 30

Prometheus指标采集与自定义指标

Actuator集成Micrometer后,/actuator/prometheus端点输出Prometheus格式指标。内置指标包含JVM内存、GC、线程池、HTTP请求延迟等。

@Service
public class OrderService {

    private final MeterRegistry meterRegistry;
    private final Counter orderCreatedCounter;
    private final Timer orderProcessingTimer;

    public OrderService(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        this.orderCreatedCounter = Counter.builder("orders.created")
            .description("Total orders created")
            .tag("type", "default")
            .register(meterRegistry);
        this.orderProcessingTimer = Timer.builder("orders.processing.time")
            .description("Order processing duration")
            .publishPercentiles(0.5, 0.95, 0.99)
            .register(meterRegistry);
    }

    public Order createOrder(OrderRequest request) {
        return orderProcessingTimer.record(() -> {
            Order order = processOrder(request);
            orderCreatedCounter.increment();
            return order;
        });
    }
}

@PostConstruct
public void initGauges() {
    meterRegistry.gauge("queue.size",
        Tags.of("name", "orderQueue"),
        orderQueue,
        q -> (double) q.size()
    );
}

Grafana中配置PromQL查询展示核心指标:

# HTTP请求P95延迟
histogram_quantile(0.95, rate(http_server_requests_seconds_bucket[5m]))

# 活跃线程数
jvm_threads_states_threads{state="runnable"}

# 自定义订单创建速率
rate(orders_created_total[5m]) * 60

# 连接池使用率
hikaricp_connections_active / hikaricp_connections_total

告警规则配置在Prometheus中,当健康检查失败或关键指标异常时触发通知。生产环境务必对Actuator端点配置Spring Security认证,限制访问来源,防止环境变量和配置信息泄露。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/springbootactuator-jian-kang-jian-cha-yu-sheng-chan-ji-jian/

(0)
小编小编
上一篇 11小时前
下一篇 11小时前

相关推荐