Prometheus 监控 Spring Boot 实战宝典:Micrometer 打通应用层可观测性的最后一公里

📅 2026/7/6 14:34:42
Prometheus 监控 Spring Boot 实战宝典:Micrometer 打通应用层可观测性的最后一公里
Prometheus 监控 Spring Boot 实战宝典Micrometer 打通应用层可观测性的最后一公里在微服务体系里Spring Boot 应用是核心业务承载体它的健康状态、吞吐量、JVM 内存、数据库连接池、自定义业务指标等必须纳入统一监控。Prometheus 生态借助Micrometer提供了完美的桥接——只需引入一个依赖就能将 Actuator 指标暴露为 Prometheus 格式。本文将带你从零集成到掌握 JVM/HTTP/业务指标、搭建 Dashboard、配置告警构建完整的应用层可观测性。1. 为什么选 Micrometer Prometheus厂商无关的指标门面Micrometer 是 Spring Boot 2/3 默认的指标库支持对接 Prometheus、Datadog、OTel 等多种后端。开箱即用的 JVM 与中间件指标内存、GC、线程、Tomcat、数据库连接池、RabbitMQ 等自动采集。自定义业务指标极其简单几行代码就能定义 Counter、Gauge、Timer。无缝集成 Prometheus暴露/actuator/prometheus端点原生直连抓取。2. 快速集成2.1 添加依赖MavendependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-actuator/artifactId/dependencydependencygroupIdio.micrometer/groupIdartifactIdmicrometer-registry-prometheus/artifactIdversion1.12.2/version!-- 根据 Spring Boot 版本匹配 --/dependencyGradleimplementation org.springframework.boot:spring-boot-starter-actuator implementation io.micrometer:micrometer-registry-prometheusSpring Boot 2.x 和 3.x 均可使用3.x 默认使用 Micrometer 1.11 并内置了 Prometheus 注册表但有时仍需显式添加依赖。2.2 配置暴露端点在application.yml或 properties中management:endpoints:web:exposure:include:health,info,prometheus,metricsendpoint:prometheus:enabled:truemetrics:export:prometheus:enabled:truetags:application:${spring.application.name}# 为所有指标打上应用名标签启动应用后访问http://localhost:8080/actuator/prometheus即可看到大量指标输出。2.3 安全控制生产环境不应公开暴露所有端点建议management:server:port:8081# 单独管理端口避免与外网端口混淆endpoints:web:exposure:include:prometheus# 仅暴露 prometheus 端点base-path:/actuator结合 Spring Security 可添加基本认证或在防火墙层面只允许 Prometheus 服务器 IP 访问管理端口。3. Prometheus 抓取配置scrape_configs:-job_name:spring-boot-appmetrics_path:/actuator/prometheusscrape_interval:15sstatic_configs:-targets:-10.0.0.50:8081# 管理端口labels:app:order-serviceenv:production如果有多个实例可使用文件发现或 K8s 服务发现。4. 核心指标解读Micrometer 自动暴露了大量指标分为 JVM 指标、系统指标、应用指标。分类指标名示例含义PromQL 示例JVM 内存jvm_memory_used_bytesjvm_memory_max_bytes堆/非堆使用量及最大值jvm_memory_used_bytes{areaheap} / jvm_memory_max_bytes{areaheap}JVM GCjvm_gc_pause_seconds_countjvm_gc_pause_seconds_sumGC 次数与累计暂停时间rate(jvm_gc_pause_seconds_sum[1m]) / rate(jvm_gc_pause_seconds_count[1m])得平均暂停时间JVM 线程jvm_threads_live_threads当前活跃线程数结合峰值jvm_threads_peak_threads分析CPUprocess_cpu_usage进程 CPU 使用率 (0~1)process_cpu_usage * 100HTTP 请求http_server_requests_seconds_counthttp_server_requests_seconds_sum请求总数与总耗时QPS:rate(http_server_requests_seconds_count[1m])平均延迟:rate(http_server_requests_seconds_sum[1m]) / rate(http_server_requests_seconds_count[1m])HTTP 状态码http_server_requests_seconds_bucket带status标签可按 status 分类统计sum(rate(http_server_requests_seconds_count{status~5..}[1m]))得 5xx 速率Tomcat 连接tomcat_threads_busy_threadstomcat_threads_config_max_threadsTomcat 忙碌线程数与最大线程数tomcat_threads_busy_threads / tomcat_threads_config_max_threads数据源连接池hikaricp_connections_activehikaricp_connections_idlehikaricp_connections_pending活跃/空闲/等待获取的连接数等待连接数hikaricp_connections_pending 0需关注日志事件logback_events_total(若集成)按级别统计日志条数rate(logback_events_total{levelerror}[1m])错误日志速率注意指标名和标签取决于 Spring Boot 版本和依赖。例如http_server_requests_seconds在 2.x 中可能为http_server_requests_seconds3.x 一致。数据库连接池默认使用 HikariCP其指标前缀为hikaricp_*。5. 自定义业务指标5.1 使用 MeterRegistry 定义importio.micrometer.core.instrument.*;ServicepublicclassOrderService{privatefinalCounterordersTotal;privatefinalTimerorderProcessingTimer;publicOrderService(MeterRegistryregistry){ordersTotalCounter.builder(orders.total).description(Total orders created).register(registry);orderProcessingTimerTimer.builder(orders.processing.time).description(Order processing duration).register(registry);}publicvoidcreateOrder(Orderorder){longstartSystem.currentTimeMillis();// ... 业务逻辑ordersTotal.increment();orderProcessingTimer.record(System.currentTimeMillis()-start,TimeUnit.MILLISECONDS);}}5.2 用Timed注解需要 AOP添加依赖spring-boot-starter-aop然后在配置类上启用TimedConfigurationEnableAspectJAutoProxypublicclassTimedConfiguration{BeanpublicTimedAspecttimedAspect(MeterRegistryregistry){returnnewTimedAspect(registry);}}在方法上使用Timed(valueorders.find.latency,extraTags{type,search})publicListOrderfindOrders(){...}5.3 Gauge 动态指标AtomicIntegerqueueSizenewAtomicInteger();registry.gauge(custom.queue.size,queueSize);// 当 queueSize 变化时指标自动更新这些自定义指标会和系统指标一起暴露在/actuator/prometheusPrometheus 抓取后可直接查询。6. Grafana 仪表盘推荐直接导入以下社区仪表盘均适配 MicrometerSpring Boot 2.x / 3.x 通用大屏Dashboard ID10254Spring Boot Micrometer包含 JVM 概览、HTTP 请求统计、Tomcat 连接、HikariCP 池、日志统计等功能全面。JVM 监控专用 (Micrometer)Dashboard ID4701JVM (Micrometer)偏重 JVM 内存、GC、线程分析。Spring Boot 指标概览Dashboard ID12900Spring Boot 2.x 3.x简洁现代风格聚焦应用健康。导入时选择 Prometheus 数据源并将application变量设置为你的应用标签即可。7. 告警规则实战groups:-name:springboot_alertsrules:-alert:SpringBootDownexpr:up{jobspring-boot-app} 0for:1mlabels:severity:criticalannotations:summary:应用 {{ $labels.app }} 实例 {{ $labels.instance }} 宕机-alert:High5xxRateexpr:sum(rate(http_server_requests_seconds_count{status~5..,jobspring-boot-app}[5m])) by (app) / sum(rate(http_server_requests_seconds_count{jobspring-boot-app}[5m])) by (app)0.01for:2mlabels:severity:criticalannotations:summary:{{ $labels.app }} 的 5xx 错误率超过 1%-alert:HighAvgResponseTimeexpr:rate(http_server_requests_seconds_sum[5m]) / rate(http_server_requests_seconds_count[5m])1for:5mlabels:severity:warningannotations:summary:{{ $labels.app }} 平均响应时间超过 1 秒-alert:JvmMemoryHighexpr:(jvm_memory_used_bytes{areaheap}/ jvm_memory_max_bytes{areaheap})0.9for:5mlabels:severity:warningannotations:summary:{{ $labels.app }} 堆内存使用率超过 90%-alert:GcPauseTooFrequentexpr:rate(jvm_gc_pause_seconds_count[10m])5for:5mlabels:severity:warningannotations:summary:{{ $labels.app }} GC 频率过高 (5次/分钟)-alert:TomcatThreadsNearMaxexpr:tomcat_threads_busy_threads / tomcat_threads_config_max_threads0.8for:2mlabels:severity:criticalannotations:summary:{{ $labels.app }} Tomcat 忙碌线程超过 80%即将拒绝请求-alert:HikariPoolConnectionPendingexpr:hikaricp_connections_pending0for:1mlabels:severity:warningannotations:summary:{{ $labels.app }} 数据库连接池出现等待可根据实际指标名称微调例如 Spring Boot 3 中http_server_requests_seconds_count前缀确定老版本可能是http_server_requests_seconds_count但基本一致。8. 进阶配置与最佳实践8.1 过滤和定制指标通过配置文件可以过滤掉不想暴露的指标减小体积management:metrics:enable:jvm:truelogback:truetomcat:truehikaricp:truedistribution:percentiles-histogram:http.server.requests:true# 开启直方图便于计算 P95/P99slo:http.server.requests:100ms,200ms,500ms,1s8.2 Spring Security 保护 Prometheus 端点BeanpublicSecurityFilterChainactuatorSecurityFilterChain(HttpSecurityhttp)throwsException{http.securityMatcher(EndpointRequest.toAnyEndpoint()).authorizeHttpRequests(auth-auth.requestMatchers(EndpointRequest.to(prometheus)).hasRole(MONITOR).anyRequest().authenticated()).httpBasic(Customizer.withDefaults());returnhttp.build();}Prometheus 侧需配置basic_authscrape_configs:-job_name:secure-springbootmetrics_path:/actuator/prometheusbasic_auth:username:monitor_userpassword:strong_passwordstatic_configs:-targets:[app:8081]8.3 Kubernetes 环境在 K8s 中部署 Spring Boot 应用无需硬编码 target可利用 Prometheus Operator 的PodMonitor或注解自动发现apiVersion:monitoring.coreos.com/v1kind:PodMonitormetadata:name:spring-boot-appspec:selector:matchLabels:app:order-servicepodMetricsEndpoints:-port:management# 管理端口名称path:/actuator/prometheus8.4 分布式链路追踪联动结合Micrometer TracingOpenTelemetry可将指标与 trace 关联Prometheus 侧虽无法直接展示 trace但可通过 Grafana Tempo/Jaeger 实现关联。9. 安全与性能注意事项指标端点不宜公网暴露始终使用独立管理端口或内部网络访问。高基数标签 (High Cardinality)是大忌避免将请求 URI 含参数等作为标签默认 Spring Boot 只保留 URI 模式 (如/users/{id})如果自定义 Tag务必控制变量。抓取频率15s~30s 足够频繁抓取会增加应用内存消耗Micrometer 内存中维持所有指标状态。升级版本Spring Boot 3.x 和 Micrometer 1.11 在性能和内存上有优化推荐使用最新稳定版。将这套方案落地后你的 Spring Boot 应用就从“黑盒”变成一个完全透明、指标驱动的可观测系统。无论是内存泄漏、接口延迟抖动、数据库连接池耗尽还是业务异常激增都能在 Grafana 上直观呈现并由 Prometheus Alertmanager 第一时间通知你。它不仅是运维者的利器更是开发人员优化性能的数据源泉。