在nodejs中初始化新数据库连接的位置? [英] Where to initialize a new database connection in nodejs?

查看:172
本文介绍了在nodejs中初始化新数据库连接的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您应该在路由处理程序的范围之外创建数据库连接的实例,或者为每个处理程序创建一个实例(例如, app.get('/ todos') )?



如果我错了,请更正我,但我猜第一种方法更好,因为它可以重复使用相同的连接。但是,我看到其他示例为每个路由处理程序创建一个。



推荐的方法是什么?还是重要的,因为数据库可以缓存连接到最后?



编辑:我可能会困惑数据库驱动程序如何连接。大多数提供了一种方法,如 connectDB(config)其中指定资源的位置,身份验证等。这实际上是建立连接还是在您启动时启动连接

解决方案

您应该连接一次,并在所有的处理程序中使用它。

如果您在每个请求上重新连接到数据库,那么您将使用大量资源并增加延迟,更不用说使用无用的重新连接来锤击数据库。



数据库连接是持久的 - 不是一次性的东西。



你没有说出你使用的数据库,但是Mongo的例子 - 当您使用原生
MongoDB Node连接到数据库时。 js驱动程序有一些您可以使用的选项,如:




  • poolSize - 设置每个服务器或代理连接的最大poolSize(默认为 5

  • autoReconnect - 重新连接错误(默认为 true



其他一些有趣的选项是: reconnectTries reconnectInterval keepAlive connectTimeoutMS socketTimeoutMS



如果您对默认值不满意,您可以更改这些选项的值,但是这些选项可用于管理长期生活的连接,而不是在每个请求上重新连接和断开连接。



欲了解更多信息,请参阅:





请参阅此答案了解更多信息:




Should you create an instance of the database connection outside the scope of route handlers, or create one for each handler (e.g., app.get('/todos'))?

Correct me if I'm wrong, but I'd guess the first approach is better because it can reuse the same connection. However, I've seen other examples that creates one for each route handler.

What's the recommended approach? Or does it matter due to how the database can cache connections on its end?

EDIT: I may be confused about how database drivers connect. Most provide a method such as connectDB(config) where you specify the location of the resource, authentication, etc. Is this actually making a connection or does it initiate the connection when you actually request something with that database object?

解决方案

You should make your connection once and use it in all handlers.

If you're reconnecting to the database on every request then you will use a lot of resources and increase latency, not to mention hammering your database with useless reconnections.

Database connections are meant to be persistent - not one-time things.

You didn't say which database you use, but on the example of Mongo - when you connect to the DB with the native MongoDB Node.js Driver there are some options that you can use, like:

  • poolSize - Set the maximum poolSize for each individual server or proxy connection (default is 5)
  • autoReconnect - Reconnect on error (default is true)

Some other interesting options are: reconnectTries, reconnectInterval, keepAlive, connectTimeoutMS, socketTimeoutMS.

You can change the values of those options if you're not happy with the defaults but those options are there to manage a long-living connection, not to reonnect and disconnect on every request.

For more info see:

See also this answer for more info:

这篇关于在nodejs中初始化新数据库连接的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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