下一个.js和MongoDB阿特拉斯 - 获得"Connections % of configured limit has gone above 80"警报



我在MongoDB Atlas上看到了很多关于此警报的帖子和文章("配置限制的连接百分比已超过80"(,但我不知道如何在Next.js应用程序中解决它。

我在处理程序函数之外创建数据库连接。我使用了一个中间件withDatabase.js:

const client = new MongoClient(process.env.MONGODB_URI, { 
useNewUrlParser: true, 
useUnifiedTopology: true 
});
const addDbToRequest = (handler, req, res) => {
req.db = req.connection.db("MYDBNAME");
return handler(req, res);
};
const withDatabase = handler => async (req, res) => {
if (!client.isConnected()) {
await client.connect();
}
req.connection = client;
return addDbToRequest(handler, req, res);
};
export default withDatabase;

该中间件封装了API端点处理程序。

现在,如果我在每个API处理程序完成时关闭连接,如下所示:

const { connection } = req;
if (connection) {
connection.close();
}

然后,我在向同一个api处理程序发送的第二个请求中遇到了一个错误:

MongoError: Topology is closed, please connect

如果我没有关闭连接,我会在我的电子邮件中收到这个警报(使用很短时间后(:

Connections % of configured limit has gone above 80

在Next.js应用程序中使用MongoDB Atlas的最佳实践是什么?

谢谢!

由于以下原因,应重新使用连接:

  1. 在每个API请求上打开和关闭DB连接都很慢
  2. 它很难扩展。假设每个用户同时发出几个API请求,当应用程序获得更多用户时,您将很快达到相同的连接限制

如何在Node.js web应用程序中管理MongoDB连接?

2022更新:

import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

2022年前

默认的MongoClient配置将每个池的最大连接数(poolSize(设置为5。因此,如果你只有一个应用程序实例在运行,并且像你一样检查客户端是否已经连接,那么在MongoDB Atlas中你不应该看到超过5个连接。

if (!client.isConnected()) {
await client.connect();
}

注意,Next.js";重新启动";在开发模式(next dev(中的每个请求上,它似乎会影响MongoClient缓存并创建许多连接。但是,在生产模式中,您不应该遇到此问题。

为了修复Next的开发模式中达到的最大连接数问题,我发现将重用/缓存的client对象写入全局Node对象可以使其在刷新之间保持不变。

const MongoClient = require('mongodb').MongoClient;
async function useMongoClient() {
if (!this.client) {
this.client = await MongoClient.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
});
}
return this.client;
}
module.exports = useMongoClient;

最新更新