简体   繁体   English

在 Node.js 中管理数据库连接,最佳实践?

[英]Managing database connections in Node.js, best practices?

I'm building an Node application which will query simple and more complex (multiple joins) queries.我正在构建一个 Node 应用程序,它将查询简单和更复杂(多个连接)的查询。 I'm looking for suggestions on how I should manage the mySQL connections.我正在寻找有关如何管理 mySQL 连接的建议。

I have the following elements:我有以下要素:

  • server.js: Express server.js:快递
  • router1.js (fictive name): Express Router middleware router1.js(虚构名称):Express Router 中间件
  • router2.js (fictive name): Express Router middleware router2.js(虚构名称):Express Router 中间件

    //this is router1

    router.get('/', function (req, res){

    connection.connect(function(Err){...});

      connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){
        console.log(results);
      });
      ...
    connection.end();
    })

Should I connect to mysql everytime '/router1/' is requested, like in this example, or it's better to leave one connection open one at start up?我是否应该在每次请求“/router1/”时连接到 mysql,就像在这个例子中一样,还是最好在启动时保持一个连接打开? As:作为:

connection.connect();
outside of: 在外面:
 router.get('/',function(req,res){... }); router.get('/',function(req,res){... });
?

I am using mysql2 for this, it is basicly mysql but with promises.我为此使用 mysql2,它基本上是 mysql,但有承诺。 If you use mysql you can also do this.如果你使用 mysql 你也可以这样做。

Create a seperate file called connection.js or something.创建一个名为 connection.js 之类的单独文件。

const mysql = require('mysql2');

const connection = mysql.createPool({
    host: "localhost",
    user: "",
    password: "",
    database: ""
    // here you can set connection limits and so on
});

module.exports = connection;

Then it is probaly better you create some models and call these from within your controllers, within your router.get('/', (req, res) => {here});然后最好创建一些模型并从控制器中调用它们,在router.get('/', (req, res) => {here});

A model would look like this:一个模型看起来像这样:

const connection = require('../util/connection');

async function getAll() {
    const sql = "SELECT * FROM tableName";
    const [rows] = await connection.promise().query(sql);
    return rows;
} 
exports.getAll = getAll;

You can do this with or without promises, it doesn't matter.你可以在有或没有承诺的情况下做到这一点,这并不重要。 Your connection to the pool is automatically released when the query is finished.查询完成后,您与池的连接将自动释放。 Then you should call getAll from your router or app.然后你应该从你的路由器或应用程序调用 getAll 。

I hope this helped, sorry if not.我希望这有帮助,如果没有,抱歉。

Connection pooling is how it should be done.连接池是应该如何完成的。 Opening a new connection for every request slows down the application and it can sooner or later become a bottleneck, as node does not automatically closes the connections unlike PHP.为每个请求打开一个新连接会减慢应用程序的速度,它迟早会成为瓶颈,因为节点不会像 PHP 那样自动关闭连接。 Thus connection pool ensures that a fixed number of connections are always available and it handles the closing of unnecessary connections as and when required.因此,连接池确保固定数量的连接始终可用,并在需要时处理关闭不必要的连接。

This is how I start my express app using Sequelize.这就是我使用 Sequelize 启动我的 Express 应用程序的方式。 For Mongoose, it is more or less simlar except the library API.对于 Mongoose,除了库 API 外,它或多或少是相似的。

const sequelize = new Sequelize('database', 'username', 'password', {
    host: 'localhost',
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
});

sequelize.authenticate()
    .then(
        // On successfull connection, open a port
        // and listen to requests. This is where the application 
        // starts listening to requests.
        () => {
            const server = http.createServer(app);
            server.listen(port);
        },
    )
    .catch(err => {
        console.error('Unable to connect to the database:', err);
        console.error('Cancelling app server launch');
    });

The app is started only after a database connection has been established.该应用程序仅在建立数据库连接后启动。 This ensures that the server won't be active without any database connection.这确保服务器在没有任何数据库连接的情况下不会处于活动状态。 Connection pool will keep the connections open by default, and use a connection out of the pool for all queries.连接池将默认保持连接打开,并使用池外的连接进行所有查询。

If you use createPool mysql will manage opening and closing connections and you will have better performance.如果您使用createPool mysql将管理打开和关闭连接,您将获得更好的性能。 It doesn't matter if you use mysql or mysql2 or sequlize.mysql还是mysql2还是sequlize都没关系。 use a separate file for createPool and export it.createPool使用单独的文件并将其导出。 You can use it everywhere.您可以在任何地方使用它。 Don't use classes and just do it functionally for better performance in nodejs.不要使用类,只是在功能上使用它以获得更好的 nodejs 性能。

> npm install mysql

mysql is a great module which makes working with MySQL very easy and it provides all the capabilities you might need. mysql 是一个很棒的模块,它使使用 MySQL 变得非常容易,并且它提供了您可能需要的所有功能。

Once you have mysql installed, all you have to do to connect to your database is一旦你安装了 mysql,你所要做的就是连接到你的数据库

var mysql = require('mysql')

var conn = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database'
})

conn.connect(function(err) {
  if (err) throw err
  console.log('connected')
})

Now you are ready to begin writing and reading from your database.现在您已准备好开始写入和读取数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM