API 健康监测:定时调用、错误检测和通知提醒
✅ 一、目标
- 定时调用某个 API(如
/api/status
)每 5 分钟一次; - 检测是否出错(如响应超时、状态码非 200 等);
- 出错自动通知你(如短信、邮件、企业微信、钉钉、Telegram 等);
- 你收到后可以及时处理或恢复服务。
🛠️ 二、技术方案
方案一:使用 Node.js 编写监控脚本 + 定时器 + 通知
你可以新建一个独立的 Node.js 脚本作为健康监控服务。
1. 示例脚本 monitor.js
js
const axios = require("axios");
const cron = require("node-cron");
const sendAlert = require("./notifier"); // 自定义的提醒模块
const MONITORED_API = "https://yourdomain.com/api/status";
async function checkAPI() {
try {
const res = await axios.get(MONITORED_API, { timeout: 5000 });
if (res.status !== 200) {
console.error("非200状态码:", res.status);
await sendAlert(`API状态异常,返回码: ${res.status}`);
} else {
console.log("API正常:", new Date().toISOString());
}
} catch (err) {
console.error("API请求失败:", err.message);
await sendAlert(`API请求失败: ${err.message}`);
}
}
// 每5分钟执行一次
cron.schedule("*/5 * * * *", checkAPI);
2. notifier.js
示例:发送通知
你可以选择任意一种通知方式:
✅ a. 使用 Server 酱(推荐)
js
const axios = require("axios");
const SCKEY = "你的Server酱Key";
module.exports = async function sendAlert(msg) {
await axios.post(`https://sctapi.ftqq.com/${SCKEY}.send`, {
title: "API监控报警",
desp: msg,
});
};
✅ b. 发邮件(nodemailer)/钉钉机器人/企业微信机器人
可根据你的偏好实现,钉钉/微信机器人也比较常用。
🚀 三、部署方式
- 把这个脚本部署到同一服务器上,用
pm2
保持常驻运行:
bash
npm install axios node-cron
pm2 start monitor.js --name api-monitor
- 也可以放在其他机器或云函数上跑定时任务,例如:
- GitHub Actions
- AWS Lambda + CloudWatch
- 阿里云函数计算 + 定时触发器
- 腾讯云云函数 + 定时器
- 云监控平台(如 Pingdom、UpTimeRobot)
✅ 四、进阶建议(可选)
- API 可返回健康信息(如连接数据库是否正常);
- 可以集成到 Prometheus + Grafana 做更复杂的监控;
- 配合日志系统,如 ELK(Elasticsearch + Logstash + Kibana);
- 可以为不同服务设置不同阈值或通知频率。