如何在 Node.js Web 应用程序中管理 MongoDB 连接? [英] How do I manage MongoDB connections in a Node.js web application?
问题描述
我正在使用 node-mongodb-native 驱动程序和 MongoDB 来编写一个网站.
I'm using the node-mongodb-native driver with MongoDB to write a website.
我有一些关于如何管理连接的问题:
I have some questions about how to manage connections:
仅对所有请求使用一个 MongoDB 连接就足够了吗?是否有任何性能问题?如果没有,我可以设置一个全局连接以在整个应用程序中使用吗?
Is it enough using only one MongoDB connection for all requests? Are there any performance issues? If not, can I setup a global connection to use in the whole application?
如果不是,我在请求到达时打开一个新连接,并在处理请求时关闭它是不是很好?打开和关闭连接是否昂贵?
If not, is it good if I open a new connection when request arrives, and close it when handled the request? Is it expensive to open and close a connection?
我应该使用全局连接池吗?我听说驱动程序有一个本机连接池.这是一个不错的选择吗?
Should I use a global connection pool? I hear the driver has a native connection pool. Is it a good choice?
如果我使用连接池,应该使用多少个连接?
If I use a connection pool, how many connections should be used?
我还有什么需要注意的吗?
Are there other things I should notice?
推荐答案
当您的应用启动并重用时,您打开 do MongoClient.connect 一次数据库对象.它不是每个 .connect 的单例连接池创建一个新的连接池.
You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.
因此,要直接回答您的问题,重用由 MongoClient.connect()
.这为您提供了池化,并且与在每个 db 操作上打开/关闭连接相比,将显着提高速度.
So, to answer your question directly, reuse the db object that results from MongoClient.connect()
. This gives you pooling, and will provide a noticeable speed increase as compared with opening/closing connections on each db action.
这篇关于如何在 Node.js Web 应用程序中管理 MongoDB 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!