node.js + mysql connection pooling

前端 未结 7 1098
执念已碎
执念已碎 2020-11-28 02:25

I\'m trying to figure out how to structure my application to use MySQL most efficent way. I\'m using node-mysql module. Other threads here suggested to use connection poolin

7条回答
  •  臣服心动
    2020-11-28 02:54

    Using the standard mysql.createPool(), connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. However if you configure it for 500 connections and use all 500 they will remain open for the durations of the process, even if they are idle!

    This means if your MySQL Server max_connections is 510 your system will only have 10 mySQL connections available until your MySQL Server closes them (depends on what you have set your wait_timeout to) or your application closes! The only way to free them up is to manually close the connections via the pool instance or close the pool.

    mysql-connection-pool-manager module was created to fix this issue and automatically scale the number of connections dependant on the load. Inactive connections are closed and idle connection pools are eventually closed if there has not been any activity.

        // Load modules
    const PoolManager = require('mysql-connection-pool-manager');
    
    // Options
    const options = {
      ...example settings
    }
    
    // Initialising the instance
    const mySQL = PoolManager(options);
    
    // Accessing mySQL directly
    var connection = mySQL.raw.createConnection({
      host     : 'localhost',
      user     : 'me',
      password : 'secret',
      database : 'my_db'
    });
    
    // Initialising connection
    connection.connect();
    
    // Performing query
    connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
      if (error) throw error;
      console.log('The solution is: ', results[0].solution);
    });
    
    // Ending connection
    connection.end();
    

    Ref: https://www.npmjs.com/package/mysql-connection-pool-manager

提交回复
热议问题