如何使用Node.js获取当月Firestore配额、指标及读写操作用量
Node.js获取Firestore读写用量实现方案
实现思路
Firestore的读写操作用量数据默认上报到Google Cloud Monitoring服务,你可以直接调用Cloud Monitoring的API拉取指定时间范围的指标数据,再匹配官方定价规则计算月度费用即可。
前置准备
- 安装Cloud Monitoring Node.js客户端:
npm install @google-cloud/monitoring - 为你的Node.js服务配置GCP服务账号,为账号授予
roles/monitoring.viewer权限,将服务账号密钥文件路径配置到环境变量GOOGLE_APPLICATION_CREDENTIALS中
核心代码示例
const { MetricServiceClient } = require('@google-cloud/monitoring'); const client = new MetricServiceClient(); // 配置你的GCP项目ID const projectId = '你的GCP项目ID'; // 统计当月第一天0点到当前时间的用量 const startTime = new Date(new Date().getFullYear(), new Date().getMonth(), 1); const endTime = new Date(); async function getFirestoreUsage(metricType) { const request = { name: `projects/${projectId}`, filter: `metric.type="${metricType}" AND resource.type="firestore_database"`, interval: { startTime: { seconds: Math.floor(startTime.getTime() / 1000), }, endTime: { seconds: Math.floor(endTime.getTime() / 1000), }, }, aggregation: { alignmentPeriod: { seconds: (endTime.getTime() - startTime.getTime()) / 1000, }, perSeriesAligner: 'ALIGN_SUM', }, }; const [response] = await client.listTimeSeries(request); let total = 0; response.forEach(point => { total += point.points[0].value.int64Value; }); return total; } // 调用获取用量并计算费用 async function calculateMonthlyCost() { // 读操作数 const readCount = await getFirestoreUsage('firestore.googleapis.com/document/read_count'); // 写操作数 const writeCount = await getFirestoreUsage('firestore.googleapis.com/document/write_count'); // 删除操作数 const deleteCount = await getFirestoreUsage('firestore.googleapis.com/document/delete_count'); console.log(`当月读操作: ${readCount}, 写操作: ${writeCount}, 删除操作: ${deleteCount}`); // 此处匹配Firestore对应区域的官方定价规则,扣除免费额度后乘以对应单价即可得到月度费用 } calculateMonthlyCost().catch(console.error);
注意事项
- 监控数据存在最多5分钟的上报延迟,月度统计场景下误差可忽略
- 如果你的项目存在多区域部署的Firestore实例,需要在filter中补充
resource.label.location="对应区域"的过滤条件,分段统计后累加 - 业务侧自行埋点统计读写量的方案可以作为备选,但存在操作漏报的风险,优先使用官方监控数据计算费用
内容的提问来源于stack exchange,提问作者Davidsal
相关产品推荐
相关产品推荐

