这个问题可能有一个明显的答案,但我似乎找不到。我在 Node 应用程序中使用 Mongoose 连接到 MongoDB 集群。有没有办法监控Mongoose使用的客户端连接池的状态?比如池中的连接数、当前从池中 check out 的连接数、 check out 连接的速率等?如果已经有一个完善的以 Prometheus 格式导出这些指标的解决方案,那就加分了。
最佳答案
您可以使用连接池事件。这些事件由指定的池相关事件触发,例如连接、关闭等。
这是一个使用 MongoDB 模块的工作示例,取自 MongoDB official docs :
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 驱动程序。
this GitHub issue中描述的方法
关于node.js - 如何监控Mongoose连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110996/