如何监控Mongoose连接池

问题描述 投票:0回答:2

这个问题可能有一个明显的答案,但我似乎找不到。我在节点应用程序中使用 Mongoose 连接到 MongoDB 集群。有没有办法监控Mongoose使用的客户端连接池的状态?比如池中的连接数、当前从池中检出的连接数、检出连接的速率等?如果已经有一个完善的解决方案以 Prometheus 格式导出这些指标,那就加分了。

node.js mongodb mongoose prometheus
2个回答
2
投票

您可以使用连接池事件。这些事件由指定的池相关事件触发,例如连接、关闭等。

这是一个使用 MongoDB 模块的工作示例,取自 MongoDB 官方文档

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:31000,localhost:31001/?replicaSet=rs';
const client = new MongoClient(url);

client.on('connectionPoolCreated', event => console.dir(event));
client.on('connectionPoolClosed', event => console.dir(event));
client.on('connectionCreated', event => console.dir(event));
client.on('connectionReady', event => console.dir(event));
client.on('connectionClosed', event => console.dir(event));
client.on('connectionCheckOutStarted', event => console.dir(event));
client.on('connectionCheckOutFailed', event => console.dir(event));
client.on('connectionCheckedOut', event => console.dir(event));
client.on('connectionCheckedIn', event => console.dir(event));
client.on('connectionPoolCleared', event => console.dir(event));

client.connect((err, client) => {
  if (err) throw err;
});

但是,如果您想在 Mongoose 中执行此操作,您可以使用

connection.getClient()
它返回底层 mongodb 客户端,绕过 mongoose 驱动程序。

此 GitHub 问题

中描述的方法

0
投票

如果您只想通过 API 获取统计信息,您可以使用此

 mongoose.connection.db?.command({ serverStatus: 1})
    .then(results => console.log("connections", results.connections))
    .catch(error => console.error("command serverStatus error: ", error));

结果你会得到类似这样的结果(与在

db.serverStatus().connections
中运行
mongosh
时得到的结果相同):

connections {
     current: 39,
     available: 51161,
     totalCreated: 740,
     rejected: 0,
     active: 21,
     threaded: 39,
     exhaustIsMaster: 0,
     exhaustHello: 2,
     awaitingTopologyChanges: 5
 }
© www.soinside.com 2019 - 2024. All rights reserved.