如何为我的整个Node.js应用程序使用相同的MySQL连接? [英] How do I use the same MySQL connection(s) for my entire Node.js app?

查看:99
本文介绍了如何为我的整个Node.js应用程序使用相同的MySQL连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 app.js 。我从那里运行我的整个应用程序。

I have an app.js. I run my entire app from there.

在app.js内部,我需要许多包含代码的文件。

Inside app.js, I require many files that have code in it.

对于这些文件中的每一个,我这样做:

For each of these files, I do this:

var mysql = require('mysql');
var mclient = mysql.createConnection({
    host: settings.MYSQL.HOST,
    user: settings.MYSQL.USER,
    password: settings.MYSQL.PASSWORD,
    database: settings.MYSQL.DB,
});

基本上,我为每个文件启动一个新连接。

Essentially, I am initiating a new connection for every file.

我希望我的app.js建立一个连接,然后在require行期间将其传递给每个文件。如何将连接传递给它们以便这些文件可以使用它?

I want my app.js to make ONE connection, and then pass it to every file during the require line. How can I pass the connection to them so those files can use it?

(或者如何将连接池传递给它们?)

(Or how can I pass a pool of connections to them?)

推荐答案

你可以创建一个单独的模块,称之为 mysqlLib.js ,它将负责创建一个池和返回的连接:

You can create a separate module, call it mysqlLib.js that will be responsible for creating a pool and returning connections:

var mysql = require("mysql");
var pool = mysql.createPool(/* credentials go here */);

exports.getConnection = function(callback) {
  pool.getConnection(function(err, conn) {
    if(err) {
      return callback(err);
    }
    callback(err, conn);
  });
};

在任何需要mysql连接的模块/文件中,你可以这样做:

and in any module/file that needs a mysql connection, you can do this:

var mysqlLib = require("mysqlLib");

mysqlLib.getConnection(function(err, mclient) {
  //do queries that you need
});

require()的方式有效, mysqlLib.js 中的代码只会运行一次,因此即使 require(mysqlLib.js} 。请参阅node.js文档的此部分模块缓存的解释。

The way require() works, the code in mysqlLib.js will only be run once so only one pool will be created even if require("mysqlLib.js"} is called in multiple files. See this section of the node.js docs for an explanation of module cacheing.

这篇关于如何为我的整个Node.js应用程序使用相同的MySQL连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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