如何在 node.js 中使用具有 mysql 连接和池的单例设计模式

How to use singleton design pattern with mysql connection and pooling in node.js

我正在使用 node-mysql 作为 orm。 (https://github.com/mysqljs/mysql)

我正在使用 MySQL 和 Node.JS 创建 REST API。早些时候我使用 MongoDB 做了同样的事情。它工作正常。 github.com/chanakaDe/Mint-REST。现在我想使用 MySQL 做同样的事情。我完成了大部分工作,但遇到了一些小问题。有很多 classes,我需要集中使用 mysql 连接。作为单例设计模式。

这是我的新仓库。 https://github.com/chanakaDe/MintRestSQL。我将展示我想在哪里使用这些模式。我这里有数据库文件。我创建了一个新的连接池。 github.com/chanakaDe/MintRestSQL/blob/master/app/util/database.js.

现在我想在我的控制器 class 中使用这个 connection/pool。因为我无法在每个控制器中创建连接 class。不 ?这些是我现在的两个控制器。 github.com/chanakaDe/MintRestSQL/blob/master/app/routes/report.js github.com/chanakaDe/MintRestSQL/blob/master/app/routes/api.js

请告诉我一个更好的方法来做到这一点。我是 node-mysql 的新手。但这是在 Node.JS 环境中使用 MySQL 的好方法,即使对于生产级系统也是如此。所以我想用这些标准做一个好的API。有没有办法使用单例模式或类似的东西并集中连接并在所有控制器中使用它????

需要一些时间来检查我的文件并理解代码。但请检查并给我一个解决方案。我尝试了很多东西,但没有用:(

欢迎您提取回购并进行任何更新

尝试将 database.js 更改为

var mysql = require('mysql');

mysql.createPool({
  host     : 'localhost', 
  user     : 'root',
  password : 'chanaka',
  database : 'shared_adult'
}).connect();

module.exports = mysql;

为到达这里的任何人(比如我)提供一个需要注入依赖项(即凭据)的替代方案。以下是将产生运行时可配置单例​​的方法:

var mysql = require('mysql'),
    db;

module.exports = {
    init: function(conf){
        if(!db){
          db = mysql.createPool({
                host: conf.host, 
                user: conf.root,
                password: conf.password,
                database: conf.database
              });
        }
    },
    get: function() {
      if(!db) {
        throw new Error('The db pool has not been initialized, call init({}) prior to get().');
      }

      return db;    
    }
};

//initialize where you access your config (which should theoretically only be one place)
var mysqlDb = require('db'); //path to above db module

mysqlDb.init({
  host: 'host',
  user: 'user',
  password: 'password',
  database: 'database'
});

//use in your modules
var mysqlDb = require('db'), //path to above db module
    db = mysqlDb.get();