简体   繁体   中英

Managing database connections in Node.js, best practices?

I'm building an Node application which will query simple and more complex (multiple joins) queries. I'm looking for suggestions on how I should manage the mySQL connections.

I have the following elements:

  • server.js: Express
  • router1.js (fictive name): Express Router middleware
  • router2.js (fictive name): Express Router middleware

    //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? As:

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

I am using mysql2 for this, it is basicly mysql but with promises. If you use mysql you can also do this.

Create a seperate file called connection.js or something.

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});

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.

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. 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. For Mongoose, it is more or less simlar except the library 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. It doesn't matter if you use mysql or mysql2 or sequlize. use a separate file for createPool and export it. You can use it everywhere. Don't use classes and just do it functionally for better performance in 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.

Once you have mysql installed, all you have to do to connect to your database is

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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