2、Prometheus 基础架构回顾:Pull 模型、时序数据库、Metric 类型、PromQL 入门
2.1 整体架构与 Pull 模型
Prometheus 采用 主动拉取(Pull) 的监控数据采集模式,区别于传统推(Push)模式。核心组件包括 Prometheus Server、Exporters、Pushgateway(辅助)、Alertmanager 以及数据可视化层(Grafana)。
Pull 模型优势: 避免目标端过载、天然支持健康探测、配置变更灵活、数据一致性高。
2.2 时序数据库(TSDB)核心特性
Prometheus 内置高性能时序数据库,专为监控指标设计。核心概念包括:
| 概念 | 说明 | 示例 |
|---|---|---|
| Metric Name | 指标名称,描述监控对象 | http_requests_total |
| Labels | 键值对标签,用于维度过滤 | {method="GET", status="200"} |
| Sample | 时间戳 + 值 | @1620000000 1024 |
| Time Series | 同一 Metric + Labels 的样本序列 | http_requests_total{method="GET"} → [(t1,v1), (t2,v2)] |
存储优化: Prometheus TSDB 采用块压缩、倒排索引、WAL 预写日志,单机可支撑百万级时间序列。
2.3 Metric 类型详解
Prometheus 客户端库提供四种核心指标类型,每种类型对应不同的监控场景和 PromQL 处理方式。
| 类型 | 语义 | 典型场景 | PromQL 常用函数 |
|---|---|---|---|
| Counter | 只增不减的累计值 | 请求总数、错误计数、CPU 时间 | rate(), increase() |
| Gauge | 可增可减的瞬时值 | 内存使用量、连接数、温度 | avg(), max(), delta() |
| Histogram | 分桶统计 + 总和 + 计数 | 请求延迟分布、响应大小 | histogram_quantile() |
| Summary | 预计算分位数 + 总和 + 计数 | SLI 延迟跟踪(客户端计算) | 直接读取 quantile 标签 |
避坑指南: Counter 不可用于瞬时下降场景;Histogram 分位数由服务端计算,Summary 由客户端计算,两者不可混用。
2.4 PromQL 入门
PromQL(Prometheus Query Language)是 Prometheus 内置的函数式查询语言,用于实时聚合与计算时序数据。
2.4.1 基础查询语法
# 查询所有 http_requests_total 时间序列
http_requests_total
# 带标签过滤
http_requests_total{job="api-server", method="GET"}
# 范围向量:过去 5 分钟
http_requests_total[5m]
# 偏移查询:1 小时前的数据
http_requests_total offset 1h
2.4.2 常用聚合与函数
| 函数/操作 | 作用 | 示例 |
|---|---|---|
rate() |
计算 Counter 每秒平均增长率 | rate(http_requests_total[5m]) |
increase() |
计算 Counter 在时间范围内的增量 | increase(http_requests_total[1h]) |
avg() |
聚合平均值 | avg(rate(http_requests_total[5m])) by (job) |
topk() |
返回前 K 个时间序列 | topk(3, rate(http_requests_total[5m])) |
histogram_quantile() |
从 Histogram 计算分位数 | histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) |
PromQL 核心原则: 对 Counter 必须先使用
rate() 或 increase() 转换为速率再聚合;Gauge 可直接聚合;Histogram 必须配合 histogram_quantile() 使用。
2.4.3 实战查询示例
# 1. 查询 API 服务 5 分钟平均 QPS,按实例分组
rate(http_requests_total{job="api-server"}[5m])
# 2. 查询 95% 请求延迟(Histogram 方式)
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, instance))
# 3. 查询当前内存使用率超过 80% 的节点
(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100 > 80
# 4. 查询过去 1 小时错误请求增量
increase(http_requests_total{status=~"5.."}[1h])
调试技巧: 在 Prometheus UI 的 Graph 页面或 Console 页面直接输入 PromQL,可实时验证查询结果;使用
label_replace() 可动态修改标签。