【基于 Swoole+Hyperf 的微服务实战】 第六周·周五:服务告警:基于 Prometheus AlertManager 配置邮件/钉钉告警
今天我们进入的主题是 服务告警:基于 Prometheus AlertManager 配置邮件/钉钉告警。昨天我们已经用 Prometheus 收集了服务指标,用 Grafana 进行了可视化,但监控离不开主动告警。当系统出现异常(如错误率飙升、延迟过高、服务宕机)时,必须第一时间通知到人。今天将搭建 AlertManager,编写告警规则,对接钉钉与邮件,并进行故障演练验证告警全链路。

今日目标
- 理解 Prometheus AlertManager 的架构:规则评估 → 告警发送 → 路由 → 接收器。
- 使用 Docker 部署 AlertManager,与 Prometheus 集成。
- 编写关键告警规则(高错误率、高延迟、服务下线、CPU/内存异常)。
- 配置钉钉 Webhook 和邮件 SMTP 接收器,实现多通道通知。
- 模拟故障(停止服务、压测导致延迟升高),触发告警,验证消息及时送达。
一、环境准备:部署 AlertManager(约 30 分钟)
1. 添加 AlertManager 到 Docker Compose
编辑 swoole-course/docker-compose.yml,在 services 下增加:
alertmanager:
image: prom/alertmanager:latest
container_name: alertmanager-lab
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml
ports:
- "9093:9093"
command:
- '--config.file=/etc/alertmanager/alertmanager.yml'
restart: unless-stopped
启动:
docker-compose up -d alertmanager
2. 准备告警规则文件和钉钉/邮件配置
我们需要两个新文件:
prometheus.yml(修改,增加 rule_files 和 alerting 配置)alertmanager.yml(AlertManager 的路由与接收器)rules.yml(告警规则)
在宿主机 swoole-course/ 目录下创建这些文件。
二、知识核心:告警规则与路由(约 1 小时)
1. AlertManager 工作流程
Prometheus Server 定期根据 rule_files 中定义的规则计算表达式,当条件满足且持续指定时间(for)后,生成告警(Alert)并推送到 AlertManager。
AlertManager 负责:
- 分组:将相同类型的告警合并,避免重复发送。
- 抑制:当某个关键告警触发时,抑制其他次要告警。
- 静默:允许在维护窗口暂停告警。
- 路由:根据标签将告警发送到不同的接收器(如钉钉、邮件、微信)。
2. 告警规则语法
一个典型的规则:
groups:
- name: service_alerts
rules:
- alert: HighErrorRate
expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "服务错误率超过5%"
description: "{{ $labels.handler }} 错误率 {{ $value | humanizePercentage }}"
expr:PromQL 表达式,返回向量。for:持续满足该条件多久才告警,防止抖动。labels:附加标签,用于路由。annotations:描述信息,可在通知模板中引用。
3. 钉钉与邮件接收器配置
AlertManager 支持通过 email_config、webhook_config 等发送通知。
- 钉钉:需要在钉钉群添加自定义机器人,获取 Webhook URL,并注意安全设置(签名或 IP)。
- 邮件:配置 SMTP 服务器及认证。
我们将使用 AlertManager 的 webhook 发送钉钉,配合 dingtalk 或通用 webhook 集成。由于钉钉 API 格式特殊,AlertManager 官方不原生支持钉钉,但可通过 prometheus-webhook-dingtalk 中间件转换,或直接使用 AlertManager 的 webhook 配置并编写简单的转发脚本。为了简化,今天采用邮件告警 + 钉钉机器人通过 Grafana 或自定义脚本 两种方式。重点演示 AlertManager 邮件告警,钉钉部分可以使用 Grafana 内置告警或展示 webhook 转发原理。
我们主要实现邮件告警,因为无需依赖外部网关,SMTP 直接可用(可使用 QQ 邮箱等测试)。钉钉告警会给出对接思路。
三、实战:配置告警规则与通知(约 2.5 小时)
步骤 1:编写告警规则文件 rules.yml
创建 rules.yml:
groups:
- name: hyperf_alerts
rules:
# 服务下线告警
- alert: ServiceDown
expr: up == 0
for: 1m
labels:
severity: critical
team: devops
annotations:
summary: "服务 {{ $labels.job }} 已下线"
description: "Prometheus 无法抓取 {{ $labels.job }} 的指标超过1分钟"
# 错误率告警
- alert: HighErrorRate
expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.05
for: 3m
labels:
severity: warning
annotations:
summary: "服务错误率过高"
description: "{{ $labels.handler }} 在5分钟内错误率 {{ $value | humanizePercentage }}"
# P99延迟告警
- alert: HighLatency
expr: histogram_quantile(0.99, rate(http_requests_duration_seconds_bucket[5m])) > 0.5
for: 5m
labels:
severity: warning
annotations:
summary: "P99延迟超过500ms"
description: "{{ $labels.handler }} P99延迟 {{ $value }}s"
# 协程数过多告警(假设存在该指标)
- alert: TooManyCoroutines
expr: hyperf_coroutine_count > 1000
for: 5m
labels:
severity: warning
annotations:
summary: "协程数超过1000"
description: "当前协程数 {{ $value }}"
步骤 2:编写 AlertManager 配置
创建 alertmanager.yml:
global:
resolve_timeout: 5m
# 路由根节点
route:
receiver: 'default-receiver'
group_by: ['alertname', 'severity']
group_wait: 10s
group_interval: 10s
repeat_interval: 1h
routes:
- match:
severity: critical
receiver: 'critical-receiver'
receivers:
- name: 'default-receiver'
email_configs:
- to: 'your-email@example.com'
from: 'alertmanager@example.com'
smarthost: 'smtp.example.com:587'
auth_username: 'your-email@example.com'
auth_password: 'your-password'
require_tls: true
send_resolved: true
- name: 'critical-receiver'
email_configs:
- to: 'oncall-email@example.com'
from: 'alertmanager@example.com'
smarthost: 'smtp.example.com:587'
auth_username: 'your-email@example.com'
auth_password: 'your-password'
require_tls: true
注意:你需要替换真实的 SMTP 配置(例如 QQ邮箱 smtp.qq.com,端口 465/587,使用授权码)。也可以使用 webhook_config 指向一个钉钉转发服务。
为了测试,我们可以暂时使用本地日志输出接收器,而不依赖外部 SMTP。AlertManager 默认会打印通知到标准输出,也可以通过 webhook 发送到一个简单的 HTTP 服务器。但今天我们先以标准输出查看告警,同时给出邮件配置模板。
步骤 3:修改 Prometheus 配置,关联告警规则
编辑 prometheus.yml,增加 rule_files 和 alerting 部分:
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets:
- 'alertmanager:9093'
rule_files:
- "/etc/prometheus/rules.yml"
scrape_configs:
- job_name: 'hyperf-gateway'
static_configs:
- targets: ['host.docker.internal:9500']
- job_name: 'hyperf-app'
static_configs:
- targets: ['host.docker.internal:9501']
同时将 rules.yml 挂载到 Prometheus 容器。修改 docker-compose.yml 中 Prometheus 的 volumes 部分,增加:
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./rules.yml:/etc/prometheus/rules.yml
- prometheus_data:/prometheus
重启 Prometheus 和 AlertManager:
docker-compose restart prometheus alertmanager
访问 Prometheus UI (http://localhost:9090),进入 Alerts,可以看到我们定义的规则,状态为绿色(未触发)。
步骤 4:模拟故障触发告警
模拟服务下线:
停止 hyperf-gateway 或 hyperf-app 服务(如 php bin/hyperf.php stop),等待约 1-2 分钟,Prometheus 中 up == 0 规则生效,状态变为 FIRING。
查看 AlertManager UI (http://localhost:9093),能看到告警信息,并且会按照分组发送通知。如果配置了邮件,会收到邮件;如果没有,查看 AlertManager 日志 docker logs alertmanager-lab,能看到通知内容。
模拟高延迟:
在某个控制器中人为增加 sleep(2),用压测工具发送请求,使得 P99 延迟超过 0.5 秒,持续 5 分钟后应触发 HighLatency 告警。
模拟错误率:
修改代码,在 /articles 接口中随机返回 500,压测一段时间,触发 HighErrorRate。
步骤 5:(可选)对接钉钉告警
若要实现钉钉告警,需要中间服务。一个简单的方法是用 prometheus-webhook-dingtalk 容器,或者自己写一个极简的 PHP 脚本来接收 AlertManager 的 webhook 并调用钉钉机器人。
简要步骤:
- 在钉钉群添加机器人,获取 Webhook URL(如
https://oapi.dingtalk.com/robot/send?access_token=xxx)。 - 编写一个简单的
app/Controller/WebhookController.php在网关或业务服务中,接收 POST 请求,格式转换后发送到钉钉。 - 在
alertmanager.yml中增加webhook_configs指向该服务。
因为时间关系,今天大家可先尝试邮件或日志方式,课后完成钉钉对接。
四、成果测试与验证(约 1 小时)
测试清单
| 检验项 | 方法 | 通过标准 |
|---|---|---|
| 告警规则可见 | Prometheus UI Alerts 页面 | 显示所有规则,无配置错误 |
| 服务下线告警 | 停止一个服务,等待 1m | 规则 FIRING,AlertManager 收到告警 |
| 告警分组 | 同时触发多个告警 | AlertManager 将它们分组(根据 group_by) |
| 通知发送 | 查看 AlertManager 日志或邮件 | 通知内容包含 summary、description、标签 |
| 告警恢复 | 重启服务,等待 resolve_timeout | 收到 Resolved 通知(如果配置了 send_resolved) |
| 延迟告警 | 压测高延迟接口,持续超过 5min | 触发 HighLatency |
| 错误率告警 | 制造 5xx 错误,持续 3min | 触发 HighErrorRate |
观察点
- 在 Prometheus 中
Alerts的状态变化:Inactive → Pending → Firing → Resolved。 - AlertManager 的
Silence和Inhibition功能可进一步探索。
五、今日作业与学习产出
- 提交配置:将
prometheus.yml、rules.yml、alertmanager.yml、docker-compose.yml等提交到 Git。 - 完善告警规则:
- 添加磁盘/内存告警(若监控了主机)。
- 为业务定义专属告警:如“订单创建失败率 > 1%”。
- 学习笔记:
- 画出 Prometheus + AlertManager 告警处理流程图。
- 总结“误告警”常见的产生原因及如何通过
for、分组、静默来减少干扰。
- 挑战任务:
- 使用 AlertManager 的模板 自定义邮件或钉钉通知的样式。
- 编写一个自动扩容触发器:当 QPS 超过阈值时,通过 webhook 调用 K8s 或 Docker Compose 扩容脚本(思路即可)。
- 实现 On-call 轮值:通过
receivers和路由实现白天夜间不同通知对象。
通过今天的学习,你的微服务监控体系终于形成了完整闭环:指标收集 → 可视化 → 异常检测 → 主动告警。这标志着你已经具备了运维生产级微服务集群的核心能力。下周我们将进入分布式事务与异步消息的深水区,继续挑战更复杂的架构难题。

472

被折叠的 条评论
为什么被折叠?



