问题描述
我在 MongoDB Atlas 上看到了很多关于此警报的帖子和文章(配置限制的连接百分比已超过 80"),但无法弄清楚如何在我的 Next.js 应用程序中解决它.
I saw a lot of posts and articles about this alert on MongoDB Atlas ("Connections % of configured limit has gone above 80"), but couldn't figure out how to solve it in my Next.js application.
我在处理程序函数之外创建了我的数据库连接.我使用了一个中间件 withDatabase.js
:
I create my db connection outside the handler function. I used a middleware 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 端点处理程序.
This middleware wraps the API endpoint handler.
现在,如果我在每个 API 处理程序完成时关闭连接,就像这样:
Now, if I close the connection on every API handler when it finishes, like this:
const { connection } = req;
if (connection) {
connection.close();
}
然后,我在对同一个 api 处理程序的第二个请求中遇到错误:
Than, I'm getting an error on the second request to the same api handler:
MongoError: Topology is closed, please connect
如果我没有关闭连接,我会在我的电子邮件中收到此警报(使用一段时间后):
And if i'm not closing the connection, i'm getting this alert (after a short time of use) to my email:
Connections % of configured limit has gone above 80
在 Next.js 应用程序中使用 MongoDB Atlas 的最佳实践是什么?
What is the best practices to work with MongoDB Atlas in a Next.js application?
谢谢!
推荐答案
连接应该重用,原因如下:
The connection should be reused for the following reasons:
- 针对每个 API 请求打开和关闭数据库连接的速度很慢.
- 它几乎不可扩展.假设您为每个用户同时发出几个 API 请求,当应用获得更多用户时,您将很快达到相同的连接限制.
如何在 Node.js Web 应用程序中管理 MongoDB 连接?
默认 MongoClient
配置将每个池的最大连接数 (poolSize
) 设置为 5
.因此,如果您只有一个应用程序实例在运行并像您一样检查客户端是否已连接,那么您在 MongoDB Atlas 中不应看到超过 5 个连接.
Default MongoClient
configuration has maximum number of connections per pool (poolSize
) set to 5
. So, you shouldn't see more than ~5 connections in MongoDB Atlas if you have only one app instance running and checking whether a client is connected already, like you do.
if (!client.isConnected()) {
await client.connect();
}
请注意,Next.js 在开发模式 (next dev
) 中的每个请求上都会重新启动",它似乎会影响 MongoClient
缓存并创建许多连接.但是,在生产模式下,您应该不会遇到此问题.
Note, that Next.js "restarts" on every request in the development mode (next dev
) and it seems it affects MongoClient
cache and creates many connections. However in production mode, you shouldn't experience this issue.
这篇关于next.js 和 mongodb 地图集 - 获得“配置限制的连接百分比已超过 80";警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!