在Google Cloud Run中运行Node.js mongoose应用程序时,MongoDB连接过多



我正在运行一个Node.js API连接到MongoDB Atlas与猫鼬。Node.js API在Google Cloud Run上运行。

我使用mongoose打开一个连接

mongoose.connect(mongoUrl);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.info("Mongo Database connected");

然后当SINGINT信号从Google Cloud Run到达时优雅地关闭与数据库的连接

process.on("SIGINT", () => gracefulShutdown(server));

const gracefulShutdown = async (apollo?: ApolloServer) => {
await mongoose.connection.close();
console.info(`MONGODB CONNECTION CLOSED!`);
await apollo.stop();
console.info(`APOLLO SERVER STOPPED!`);
process.exit();
};

它正在正常工作,因为我可以看到日志MONGODB CONNECTION CLOSED!

但是,即使Cloud Run实例从未超过5或6个,到DB的连接数也会上升到130个。

我在这里错过了什么吗?

我想我解开了这个谜。根据mongoose文档

maxPoolSize - The maximum number of sockets the MongoDB driver will keep open for this connection. By default, maxPoolSize is 100. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. You may want to decrease maxPoolSize if you are running into connection limits

我使用Apollo graphql Server。当您链接解析器时,它们作为承诺运行,因此,mongoose可以为一个API调用启动多达100个连接。如果您查询一个id数组来构建响应对象,则可能发生这种情况。

为什么这发生在Cloud Run而不是GKE ?因为Cloud Run可以按需快速地部署服务实例,而在GKE上,您通常会限制pod的数量。因此,为了响应5个API调用,Cloud Run可以并行部署5个容器,从而扩展到多达500个Mongo连接,然后关闭实例。使用GKE就不会发生这种情况。

相关内容

最新更新