MongoDB中的maxConnectionIdleTime
参数用于设置连接在空闲状态下的最大时间,超过这个时间后,连接将被自动关闭。这个参数有助于管理数据库连接资源,防止因长时间空闲的连接占用资源而导致性能下降。
maxConnectionIdleTime
值:maxConnectionIdleTime
值:以下是一个简单的Node.js示例,展示了如何设置maxConnectionIdleTime
并确保连接正确关闭:
const MongoClient = require('mongodb').MongoClient;
async function main() {
const uri = "mongodb://localhost:27017";
const options = {
maxPoolSize: 10,
maxIdleTimeMS: 30000 // 设置空闲时间为30秒
};
const client = new MongoClient(uri, options);
try {
await client.connect();
console.log("Connected to MongoDB");
const database = client.db('testdb');
const collection = database.collection('testcollection');
// 插入一条文档
const result = await collection.insertOne({ name: "John Doe" });
console.log(`Inserted document with _id: ${result.insertedId}`);
} catch (err) {
console.error("Error:", err);
} finally {
await client.close();
console.log("Disconnected from MongoDB");
}
}
main().catch(console.error);
通过合理设置maxConnectionIdleTime
并确保应用程序正确管理连接,可以有效提升数据库的性能和稳定性。
领取专属 10元无门槛券
手把手带您无忧上云