为Node.js后端搭建Grafana实现API请求追踪、CPU监控及健康检查
实现Node.js单个API的每秒请求数监控(结合Grafana)
一、核心方案说明
Grafana仅负责可视化展示,需要搭配Prometheus做指标采集与存储,再通过Node.js的prom-client库生成API请求计数指标,最终在Grafana中通过PromQL查询实现单API的QPS(每秒请求数)监控。
二、Node.js服务端集成指标采集
- 安装依赖
npm install prom-client
- 代码集成(以Express框架为例)
const express = require('express'); const { Counter, register } = require('prom-client'); const app = express(); // 定义带路径、方法标签的请求计数器 const apiRequestCounter = new Counter({ name: 'api_requests_total', help: 'Total count of API requests', labelNames: ['path', 'method'] }); // 全局中间件:对所有API请求计数(排除metrics自身端点) app.use((req, res, next) => { if (!req.path.startsWith('/metrics')) { // 对动态路径(如/api/products/:id)可统一标准化为/api/products/:id const standardizedPath = req.path.replace(/\/\d+/g, '/:id'); apiRequestCounter.inc({ path: standardizedPath, method: req.method }); } next(); }); // 暴露Prometheus抓取用的metrics端点 app.get('/metrics', async (req, res) => { res.set('Content-Type', register.contentType); res.send(await register.metrics()); }); // 示例:你的products API app.get('/api/products', (req, res) => { res.json({ data: ['product1', 'product2'] }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
如果只想单独统计/api/products,也可以直接在该路由内调用apiRequestCounter.inc({ path: '/api/products', method: 'GET' }),跳过全局中间件。
三、配置Prometheus抓取指标
编辑Prometheus配置文件(通常为prometheus.yml),添加Node.js服务的抓取目标:
scrape_configs: - job_name: 'nodejs_api' scrape_interval: 15s # 每15秒抓取一次指标 static_configs: - targets: ['<你的Node.js服务IP>:3000'] # 替换为实际服务地址
重启Prometheus使配置生效。
四、Grafana中创建QPS可视化面板
- 确保Grafana已添加Prometheus作为数据源
- 创建新面板,选择Prometheus数据源
- 在查询编辑器中输入PromQL语句,计算
/api/products的每秒请求数:
rate(api_requests_total{path="/api/products", method="GET"}[1m])
该语句会计算最近1分钟内目标API的平均每秒请求速率
4. 选择折线图作为可视化类型,调整时间范围即可看到实时QPS数据
额外优化
- 可在计数器中添加
status_code标签,统计不同HTTP状态的请求数 - 对高频动态路径做标准化处理,避免生成过多无意义的标签值
内容的提问来源于stack exchange,提问作者N Sharma
相关产品推荐
相关产品推荐

