javascript 用于创建一次数据库连接的 node.js 设计模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6275643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:07:50  来源:igfitidea点击:

node.js design pattern for creating db connection once

javascriptdatabasedesign-patternsnode.js

提问by MarcWan

I am looking for help with a design pattern for creating a database connection in my node.js application.

我正在寻求有关在我的 node.js 应用程序中创建数据库连接的设计模式的帮助。

It seems obvious to do:

这样做似乎很明显:

module1:

模块1:

var db;
exports.get_db = function(callback) {

  if (db == null) {
    dblibrary.create(connection_params, function(error, conn) {
      if (error == null) {
        db = conn;
        callback(null, db);
      }
    });
  } else {
    callback(null, db);
  }
};

module2:

模块2:

exports.do_something = function () {
  module1.get_db(function (err, conn) {
    if (err == null) {
      // continue using query
    }
  });
};

It seems painful to have to penalize every single person who wants to get the db connection with the requirement of using a callback.

必须惩罚每个想要使用回调的数据库连接的人,这似乎很痛苦。

I could do this:

我可以这样做:

module1:

模块1:

var db;

dblibrary.create_connection(connection_params, function (err, conn) {

  if (err != null) {
     console.log("can't create connection");
     console.log(err);
     process.exit();
  } else {
     db = conn;
  }
});

exports.get_db = function() {
  return db;
};

This makes it so that getting the db connection is simple and fast, but means we have to "wait" at node startup time for the connection to be established.

这使得获取 db 连接既简单又快速,但这意味着我们必须在节点启动时“等待”建立连接。

Which is the better design? Is there a better way of doing things?

哪个设计更好?有没有更好的做事方式?

采纳答案by MarcWan

Best answer I've seen for this is:

我见过的最佳答案是:

in start.js:

在 start.js 中:

    function init_done() {

      app.listen(8080);

    }


init_databases(init_done);

in databases.js:

在 database.js 中:

init_databases(init_done_cb) {

  db.create_async(/* connect data */ , function (err, res) {

    if (err == null) init_done_cb();

  });
}

This way you can do the async startup of the database server without that awkward / dangerous waiting period.

通过这种方式,您可以异步启动数据库服务器,而无需那种尴尬/危险的等待期。

回答by alienhard

mydb.jsmodule:

mydb.js模块:

var db
exports.db = function() {
    if (db === null) {
        db = dblibrary.createClient()
    }
    return db
}

Other modules:

其他模块:

var db = require('mydb').db()
...
db.query(...)

This creates the DB client instance once at startup. I like this solution because the creation code is encapsulated in a separate module and the other modules can get access to the client with one require() statement.

这将在启动时创建一次数据库客户端实例。我喜欢这个解决方案,因为创建代码被封装在一个单独的模块中,其他模块可以通过一个 require() 语句访问客户端。

回答by floatdrop

I wrote connect-oncejust for solving this kind of problems. There are two main goals, that are achived by this module:

我写connect-once就是为了解决这类问题。该模块实现了两个主要目标:

  1. Connection should be initialized before request arrives
  2. Connection should be initialized once, even there are multiple requests coming in at the same time
  1. 连接应该在请求到达之前初始化
  2. 连接应该初始化一次,即使有多个请求同时传入

You can look at express-mongo-dband express-mongoose-dbas examples of usage.

您可以查看express-mongo-dbexpress-mongoose-db作为用法示例。