1. 为什么需要生产级监控体系?
在微服务架构中,服务实例数量可能达到数十甚至上百个,传统的日志排查方式已经无法满足运维需求。我曾经参与过一个电商项目,某个商品服务在凌晨2点出现内存泄漏,由于缺乏实时监控,直到早上用户投诉才发现问题,直接导致数百万GMV损失。
Spring Boot Actuator + Prometheus + Grafana这套组合拳,正好解决了三个核心痛点:
- 指标暴露(Actuator)
- 指标采集存储(Prometheus)
- 可视化告警(Grafana)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 监控体系架构设计
2.1 组件分工图解
code复制[Spring Boot应用] --暴露指标--> [Prometheus] --提供数据--> [Grafana]
↑ ↑
|__ Actuator Endpoints |__ 定时Pull模式采集
2.2 版本选型建议
- Spring Boot 2.7.x(最新稳定版)
- Prometheus v2.40+(支持新式服务发现)
- Grafana 9.3.x(优化了告警规则编辑器)
重要提示:生产环境务必保持组件版本一致,避免兼容性问题。我曾在升级Prometheus时因版本跳跃导致指标丢失。
3. Spring Boot应用配置
3.1 Actuator关键配置
yaml复制management:
endpoints:
web:
exposure:
include: "*" # 生产环境建议精确控制暴露的端点
endpoint:
health:
show-details: always
prometheus:
enabled: true
metrics:
export:
prometheus:
enabled: true
tags:
application: ${spring.application.name} # 重要!为指标添加应用标签
3.2 必须启用的健康指标
java复制@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags(
"region", System.getenv("REGION"),
"zone", System.getenv("ZONE")
);
}
4. Prometheus深度配置
4.1 抓取配置最佳实践
yaml复制scrape_configs:
- job_name: 'spring-apps'
metrics_path: '/actuator/prometheus'
scrape_interval: 15s
static_configs:
- targets: ['app1:8080', 'app2:8080']
relabel_configs:
- source_labels: [__address__]
target_label: instance
- source_labels: [__meta_kubernetes_pod_name] # K8s环境专用
target_label: pod
4.2 存储优化参数
yaml复制storage:
tsdb:
retention: 30d # 根据磁盘容量调整
wal_compression: true # 减少磁盘占用
5. Grafana高阶使用
5.1 仪表盘模板导入
- 搜索ID为4701的JVM监控模板
- 导入时选择关联的Prometheus数据源
- 设置变量:$application=你的应用名
5.2 告警规则配置示例
json复制{
"alert": "HighErrorRate",
"expr": "rate(http_server_requests_errors_total{application=\"$application\"}[5m]) > 0.1",
"for": "10m",
"annotations": {
"summary": "High error rate on {{ $labels.instance }}",
"description": "Error rate is {{ $value }}"
}
}
6. 生产环境调优经验
6.1 性能优化参数
- Prometheus:
--storage.tsdb.max-block-duration=2h(降低内存占用) - Grafana:
[security] cookie_secure=true(启用HTTPS时必设)
6.2 监控指标黄金组合
- JVM内存:
jvm_memory_used_bytes - GC次数:
jvm_gc_pause_seconds_count - 线程状态:
jvm_threads_states_threads - 接口耗时:
http_server_requests_seconds_sum
7. 故障排查实录
7.1 常见问题速查表
| 现象 | 可能原因 | 解决方案 |
|---|---|---|
| 指标缺失 | Actuator端点未暴露 | 检查management.endpoints.web.exposure.include |
| Prometheus连接失败 | 网络策略限制 | 添加ServiceMonitor或PodMonitor |
| Grafana面板无数据 | 时间范围设置错误 | 检查右上角时间选择器 |
7.2 内存泄漏排查案例
通过观察jvm_memory_used_bytes{area="heap"}指标持续增长,结合jvm_gc_pause_seconds_sum的频繁GC,最终定位到是缓存未设置TTL导致。
8. 安全加固方案
8.1 访问控制三重防护
- Prometheus: 启用
--web.config.file配置TLS - Grafana: 设置
[auth.anonymous] enabled=false - Actuator: 配置
management.server.port使用独立端口
8.2 敏感指标过滤
java复制@Bean
PublicMetricsFilter metricsFilter() {
return new PublicMetricsFilter()
.deny("hystrix", "env");
}
这套监控体系在我们金融级项目中稳定运行3年,日均处理20亿+指标数据。关键是要根据实际业务特点调整采集频率和存储策略,比如交易类系统需要更密集的采集间隔(建议5s),而内容管理系统可以放宽到30s。
