【 Spring Boot Actuator 与可观测性实战】

发布时间:2026/7/27 7:46:30

【 Spring Boot Actuator 与可观测性实战】 Spring Boot Actuator 与可观测性实战从健康检查到 TraceId线上出问题时最怕两件事一是不知道服务还健不健康二是日志里找不到同一条请求的完整链路。Spring Boot Actuator、Micrometer 与 MDC 恰好补上这两块缺口。本文用一套可落地的配置把健康检查、指标导出和请求追踪串起来。为什么需要可观测性应用一旦部署到多实例环境仅靠「进程还在」远远不够。数据库连接池打满、Redis 抖动、消息中间件不可达都可能让接口大面积失败而进程本身仍在运行。可观测性通常拆成三块维度回答的问题常见手段健康检查现在能不能接流量Actuator/health指标哪里变慢、哪里变满Micrometer Prometheus日志追踪这次请求经过了哪些节点MDC 中的traceId下面按接入顺序实战。一、引入 ActuatorMavendependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-actuator/artifactId/dependencyGradleimplementation org.springframework.boot:spring-boot-starter-actuator启动后默认会暴露少量端点。生产环境不要一上来把所有端点全部放开先从health、info、metrics开始。二、暴露核心端点application.yml示例management:endpoints:web:exposure:include:health,info,metrics,prometheusendpoint:health:show-details:when_authorized# 开发可改为 alwaysinfo:env:enabled:truemetrics:tags:application:${spring.application.name}常用端点说明端点用途/actuator/health聚合健康状态供 K8s / 负载均衡探活/actuator/info应用元信息版本、构建号等/actuator/metrics指标目录与单个指标查询/actuator/prometheusPrometheus 抓取格式需额外依赖安全建议生产环境用 Spring Security 限制/actuator/**探活只暴露health指标走内网或独立端口show-details勿对公网匿名返回依赖细节可用独立管理端口与业务端口隔离management:server:port:8081三、自定义 Health IndicatorActuator 对 DataSource、Redis、RabbitMQ 等常见中间件通常自带检查。一旦依赖不在默认列表里或需要更细的业务判定就要写自定义 Indicator。1. 通用自定义示例以「外部向量检索服务」为例也可换成任意 HTTP / gRPC 依赖ComponentpublicclassVectorStoreHealthIndicatorimplementsHealthIndicator{privatefinalVectorStoreClientclient;publicVectorStoreHealthIndicator(VectorStoreClientclient){this.clientclient;}OverridepublicHealthhealth(){try{longlatencyMsclient.ping();returnHealth.up().withDetail(latencyMs,latencyMs).build();}catch(Exceptionex){returnHealth.down(ex).withDetail(reason,vector store unreachable).build();}}}2. Redis 业务级检查默认 Redis Health 只能证明「能连上」。若还要确认关键 Key 可读ComponentpublicclassRedisBizHealthIndicatorimplementsHealthIndicator{privatefinalStringRedisTemplateredis;publicRedisBizHealthIndicator(StringRedisTemplateredis){this.redisredis;}OverridepublicHealthhealth(){try{Stringpongredis.getConnectionFactory().getConnection().ping();returnPONG.equalsIgnoreCase(pong)?Health.up().withDetail(ping,pong).build():Health.down().withDetail(ping,pong).build();}catch(Exceptionex){returnHealth.down(ex).build();}}}3. 健康分组存活与就绪K8s 场景建议拆开management:endpoint:health:probes:enabled:truehealth:livenessState:enabled:truereadinessState:enabled:truegroup:readiness:include:readinessState,db,redis,rabbitliveness:include:livenessStateliveness进程是否该被重启尽量别绑外部依赖readiness是否可以接流量可绑 DB / Redis / MQ访问示例/actuator/health/liveness/actuator/health/readiness四、Micrometer Prometheus 导出指标1. 依赖dependencygroupIdio.micrometer/groupIdartifactIdmicrometer-registry-prometheus/artifactId/dependency引入后可访问/actuator/prometheus。2. 自动能拿到什么在典型 Web JDBC 应用中常见指标包括JVM堆内存、GC、线程数HTTP请求耗时、状态码分布连接池活跃连接、等待线程如 HikariCP自定义 Timer / CounterHikariCP 示例确认连接池注册到 Micrometerspring:datasource:hikari:pool-name:main-poolmaximum-pool-size:203. 业务自定义指标ServicepublicclassOrderMetrics{privatefinalCounterpaidCounter;privatefinalTimerpayTimer;publicOrderMetrics(MeterRegistryregistry){this.paidCounterCounter.builder(order.paid.count).description(成功支付订单数).register(registry);this.payTimerTimer.builder(order.pay.latency).description(支付耗时).register(registry);}publicvoidrecordPaid(RunnablepayAction){payTimer.record(payAction);paidCounter.increment();}}4. Prometheus 抓取配置scrape_configs:-job_name:spring-appsmetrics_path:/actuator/prometheusstatic_configs:-targets:[app-1:8081,app-2:8081]Grafana 可直接用 JVM / Spring Boot 官方 Dashboard再叠加业务面板支付成功率、队列积压、连接池使用率。五、日志接入 TraceIdMDC指标告诉你「系统慢了」日志告诉你「这一次请求慢在哪」。用 MDCMapped Diagnostic Context把traceId写入每条日志是成本最低的链路串联方式。1. 过滤器生成 / 透传 TraceIdComponentOrder(Ordered.HIGHEST_PRECEDENCE)publicclassTraceIdFilterextendsOncePerRequestFilter{publicstaticfinalStringTRACE_IDtraceId;publicstaticfinalStringHEADERX-Trace-Id;OverrideprotectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainfilterChain)throwsServletException,IOException{StringtraceIdrequest.getHeader(HEADER);if(traceIdnull||traceId.isBlank()){traceIdUUID.randomUUID().toString().replace(-,);}MDC.put(TRACE_ID,traceId);response.setHeader(HEADER,traceId);try{filterChain.doFilter(request,response);}finally{MDC.remove(TRACE_ID);}}}2. Logback 模式带上 TraceIdpattern%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} [traceId%X{traceId}] - %msg%n/pattern日志效果2026-07-20 22:01:12.331 [http-nio-8080-exec-3] INFO c.e.order.PayService [traceIda1b2c3d4e5] - pay start 2026-07-20 22:01:12.410 [http-nio-8080-exec-3] INFO c.e.order.PayService [traceIda1b2c3d4e5] - pay success排查时用traceId在日志平台检索即可还原单次请求上下文。3. 异步与线程池注意点线程切换会丢掉 MDC。提交异步任务前要手动传递MapString,StringcontextMDC.getCopyOfContextMap();executor.execute(()-{if(context!null){MDC.setContextMap(context);}try{// 业务逻辑}finally{MDC.clear();}});若已使用 Micrometer Tracing / OpenTelemetry可进一步与 Zipkin、Jaeger 对接MDCtraceId仍是日志侧的最小可用方案。六、落地检查清单接入完成后建议按下面清单自测/actuator/health返回UP人为停 Redis 后 readiness 变为DOWN/actuator/info能看到构建版本或 Git 提交/actuator/prometheus能看到jvm_memory_used_bytes、http_server_requests_seconds发一笔请求日志中出现统一traceId响应头带回同一值Actuator 端口或路径已做鉴权 / 网络隔离七、常见坑现象可能原因处理health一直DOWN某个弱依赖被算进默认聚合用 health group或把非关键依赖标为非必需Prometheus 抓不到未加micrometer-registry-prometheus或未暴露端点检查依赖与exposure.include日志没有traceIdpattern 未写%X{traceId}或异步丢了 MDC改 pattern线程池透传 MDC探活误杀实例liveness 绑了外部依赖liveness 只看进程自身小结Actuator解决「能不能接流量」Micrometer Prometheus解决「哪里在变差」MDC TraceId解决「这一次请求怎么串起来」三者不必一次上齐全家桶先暴露health再导出prometheus最后补traceId通常一周内就能把线上可观测性从「盲飞」拉到「可定位」。后续若流量与团队规模上来再引入完整 Tracing 与统一告警规则即可。

相关新闻