MongoDB-打开和关闭连接-建议好的做法 [英] MongoDB - open and close connection - advise for good practice

查看:177
本文介绍了MongoDB-打开和关闭连接-建议好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过其用于node.js的驱动程序使用MongoDB

I am using MongoDB via its driver for node.js

通常,我需要执行操作时随时打开连接(通过connect()方法),并在完成后立即关闭连接(通过close()方法).当然,在我的程序中,我需要对MongoDB执行许多操作,因此碰巧我多次打开和关闭连接.

I typically open a connection (via the connect() method) any time I need to perform an operation and close it (via the close() method) as soon as I am finished. In my programs, as natural, I need to perform many operations against the MongoDB and therefore it happens that I open and close many times the connection.

我想知道这是一个好习惯还是在执行第一个操作时打开连接,将其存储在变量中,并使用已打开的连接进行以下操作,以便在程序结束时将其关闭会更好呢?

I am wondering whether this is a good practice or whether it would be better to open the connection as the first operation is executed, store it in a variable and use the already opened connections for the following operations closing it when the program ends.

非常感谢任何建议.

推荐答案

最佳做法是一次打开连接,将其存储在变量中,然后最后将其关闭. MongoDB明确建议这样做.这就是为什么打开和关闭连接是MongoDB API的一部分,而不是让每个查询自动发生的原因.

It is best practice to open the connection once, store it in a variable and close it at the end. MongoDB explicitly recommends this. This is the reason why opening and closing a connection is part of the MongoDB API rather than have it happen automatically for each query.

打开和关闭每个查询的连接不仅会给客户端而且会给服务器本身带来大量的性能(CPU +延迟),网络流量,内存管理(创建和删除对象)方面的开销,这也会影响其他客户.

Opening and closing connections for each query will introduce a significant overhead both in terms of performance (CPU + latency), network traffic, memory management (creating and deleting objects), not only for the client but also for the server itself, which also impacts other clients.

关于连接的术语:在某些驱动程序(如Java)中,实际创建并存储在变量中的不是物理连接,而是MongoClient实例.从抽象(API)角度看,它看起来像一个连接,但实际上封装了实际的物理连接,并向用户隐藏了复杂性.

About the terminology of connection: in some drivers like Java, what is actually created and stored in a variable is not a physical connection, but a MongoClient instance. It looks like a connection from an abstract (API) perspective, but it actually encapsulates the actual physical connection(s) and hides complexity from the user.

对于支持该驱动程序的驱动程序,仅创建一次MongoClient实例也将使您受益于连接池,在该驱动程序中,驱动程序将为您并行维护活动的连接.只需跨多个线程创建一个MongoClient实例.

Creating the MongoClient instance only once, for the drivers that support this, will also allow you to benefit from connection pooling where the driver maintains active connections in parallel for you, so that you also only need to create one MongoClient instance across multiple threads.

这篇关于MongoDB-打开和关闭连接-建议好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆