性能优化
Grafana 性能优化涉及查询优化、缓存配置、资源调整等多个方面。
查询优化
查询性能问题
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 查询慢 | 高基数标签 | 减少标签组合 |
| 面板加载慢 | 多个复杂查询 | 合理分组 |
| 响应超时 | 大范围查询 | 缩小时间范围 |
| 资源占用高 | 频繁刷新 | 增大刷新间隔 |
PromQL 优化
promql
# 避免高基数查询
# 不推荐
sum(rate(http_requests_total[5m])) by (user_id)
# 推荐 - 使用低基数标签
sum(rate(http_requests_total[5m])) by (service, method)
# 预聚合查询
# 使用 recording rules
record: http_requests_total:rate5m
expr: sum(rate(http_requests_total[5m])) by (service)Recording Rules
yaml
# Prometheus recording rules
groups:
- name: grafana_rules
interval: 30s
rules:
- record: job:http_requests:rate5m
expr: sum(rate(http_requests_total[5m])) by (job)
- record: job:http_errors:rate5m
expr: sum(rate(http_requests_total{status=~"5.."}[5m])) by (job)
- record: job:error_rate:ratio5m
expr: job:http_errors:rate5m / job:http_requests:rate5m查询缓存
yaml
# grafana.ini
[query_cache]
enabled = true
# 缓存大小
max_size_mb = 100
# 缓存 TTL
default_ttl = 5m数据源优化
Prometheus 数据源
yaml
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
# Grafana 数据源配置
jsonData:
httpMethod: POST
customQueryParameters: ""
timeout: 30MySQL 数据源
yaml
# 优化 SQL 查询
SELECT
UNIX_TIMESTAMP(time_column) as time_sec,
value,
metric_name as metric
FROM metrics_table
WHERE time_column BETWEEN $__timeFrom() AND $__timeTo()
ORDER BY time_column
LIMIT 1000
# 使用索引
CREATE INDEX idx_time ON metrics_table(time_column);Elasticsearch 数据源
yaml
# 优化查询
jsonData:
esVersion: "7.10.0"
timeField: "@timestamp"
maxConcurrentShardRequests: 5
# 使用查询优化
{
"query": {
"bool": {
"must": [
{"range": {"@timestamp": {"gte": "now-1h"}}}
]
}
},
"size": 100
}仪表板优化
面板数量控制
yaml
# 最佳实践
- 每个仪表板不超过 20 个面板
- 相关面板分组显示
- 使用行折叠不常用面板
- 使用变量减少面板数量时间范围优化
yaml
# 推荐时间范围
- 实时监控: 1h - 6h
- 趋势分析: 24h - 7d
- 历史查询: 30d - 90d
# 面板级别时间范围
{
"timeFrom": "now-6h",
"timeShift": null
}刷新间隔优化
yaml
# 推荐刷新间隔
- 关键仪表板: 10s - 30s
- 一般仪表板: 1m - 5m
- 历史仪表板: 5m - 15m 或手动
# 配置
{
"refresh": "30s"
}使用变量
json
{
"templating": {
"list": [
{
"name": "service",
"type": "query",
"query": "label_values(up, job)",
"multi": true
}
]
}
}缓存配置
查询缓存
yaml
# grafana.ini
[caching]
enabled = true
[query_cache]
enabled = true
max_size_mb = 100
default_ttl = 5m
[dataproxy]
# 数据代理缓存
caching_enabled = true
caching_ttl = 5mDashboard 缓存
yaml
# grafana.ini
[dashboards]
# 启用仪表板缓存
versions_to_keep = 20
min_refresh_interval = 5s
default_home_dashboard_path = /dashboards/home.json浏览器缓存
yaml
# nginx.conf
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}资源配置
Grafana 配置
yaml
# grafana.ini
[server]
# HTTP 赶时
http_timeout = 30s
# 并发请求限制
[dataproxy]
max_idle_connections = 100
idle_connection_timeout = 90s
# 内存限制
[alerting]
max_attempts = 3
execute_alerts = trueDocker 资源限制
yaml
services:
grafana:
image: grafana/grafana:10.4.0
deploy:
resources:
limits:
cpus: '2'
memory: 2G
reservations:
cpus: '1'
memory: 1GKubernetes 资源
yaml
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "2Gi"
cpu: "2000m"插件优化
插件管理
bash
# 查看已安装插件
grafana-cli plugins ls
# 安装必要插件
grafana-cli plugins install grafana-clock-panel
# 移除不必要插件
grafana-cli plugins remove plugin-name
# 更新插件
grafana-cli plugins update-all插件配置
yaml
# grafana.ini
[plugins]
# 启用插件预加载
enable_alpha = false
allow_loading_unsigned_plugins = plugin-id
[plugin.grafana-clock-panel]
# 插件特定配置
path = /var/lib/grafana/plugins/grafana-clock-panel告警优化
告警规则优化
yaml
# 使用预聚合
groups:
- name: alert_rules
rules:
- alert: HighErrorRate
expr: job:error_rate:ratio5m > 0.05
for: 5m
- alert: HighCPUUsage
expr: instance:cpu_usage:rate5m > 0.8
for: 10m告警分组
yaml
# Notification Policies
policies:
- receiver: default-receiver
group_by: [alertname, severity]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h告警抑制
yaml
# 维护窗口抑制
muteTimings:
- name: maintenance-window
time_intervals:
- start_time: "22:00"
end_time: "06:00"监控 Grafana 性能
Grafana 内置指标
yaml
# grafana.ini
[metrics]
enabled = true
interval_seconds = 10Grafana 指标查询
promql
# API 响应时间
histogram_quantile(0.95,
sum(rate(grafana_api_response_time_seconds_bucket[5m])) by (le)
)
# 活跃会话数
grafana_active_sessions_count
# 数据源查询总数
sum(rate(grafana_datasource_query_total[5m])) by (datasource)
# 仪表板总数
grafana_dashboards_count
# 错误总数
sum(rate(grafana_api_error_total[5m])) by (status)Grafana 监控仪表板
json
{
"title": "Grafana Performance",
"panels": [
{
"type": "timeseries",
"title": "API Response Time",
"targets": [
{
"expr": "histogram_quantile(0.95, sum(rate(grafana_api_response_time_seconds_bucket[5m])) by (le))"
}
]
},
{
"type": "stat",
"title": "Active Sessions",
"targets": [
{
"expr": "grafana_active_sessions_count"
}
]
},
{
"type": "timeseries",
"title": "Query Rate",
"targets": [
{
"expr": "sum(rate(grafana_datasource_query_total[5m])) by (datasource)",
"legendFormat": "{{datasource}}"
}
]
}
]
}性能问题排查
慢查询排查
bash
# 检查 Grafana 日志
docker logs grafana | grep "slow"
# 检查 Prometheus 查询
curl 'http://localhost:9090/api/v1/query?query=http_requests_total'
# 分析查询性能
curl 'http://localhost:9090/api/v1/status/tsdb'资源瓶颈
bash
# 检查 Grafana 进程
top -p $(pgrep grafana)
# 检查内存使用
docker stats grafana
# 检查数据库性能
psql -U grafana -c "SELECT count(*) FROM dashboard;"网络问题
bash
# 测试数据源连通性
curl http://localhost:9090/-/healthy
# 测试 API 响应时间
curl -w "@curl-format.txt" http://localhost:3000/api/health最佳实践
- 查询优化:使用预聚合和低基数标签
- 缓存配置:启用查询缓存和数据代理缓存
- 仪表板设计:控制面板数量,使用变量分组
- 时间范围:根据需求设置合理时间范围
- 刷新间隔:避免过于频繁的刷新
- 资源限制:设置合理的 CPU 和内存限制
- 监控告警:监控 Grafana 自身性能
- 定期清理:清理不用的仪表板和数据源
参考:https://grafana.com/docs/grafana/latest/setup-grafana/performance/