【问题标题】:NodeJS + mysql - automatically closing pool connections?NodeJS + mysql - 自动关闭池连接?
【发布时间】:2016-11-01 10:49:25
【问题描述】:

我希望使用 NodeJS 和 MySQL 数据库的连接池。根据文档,有两种方法可以做到这一点:或者我明确地从池中获取连接,使用它并释放它:

var pool = require('mysql').createPool(opts);

pool.getConnection(function(err, conn) {
    conn.query('select 1+1', function(err, res) {
        conn.release();
    });
});

或者我可以这样使用它:

var mysql = require('mysql');
var pool  = mysql.createPool({opts});

pool.query('select 1+1', function(err, rows, fields) {
  if (err) throw err;

  console.log('The solution is: ', rows[0].solution);
});

如果我使用第二个选项,这是否意味着连接会自动从池中拉出、使用和释放?如果是这样,是否有理由使用第一种方法?

【问题讨论】:

  • 第一种情况在您打算使用连接对象进行某些操作时特别有用,而连接对象在池的情况下不可用。另一方面,当您只关心执行查询并让连接由 node-mysql 池功能管理时,池很有用。

标签: mysql node.js connection-pooling


【解决方案1】:

是的,第二个意味着池负责获取下一个空闲连接对其进行查询,然后再次释放它。您可以将它用于“one shot” 没有依赖关系的查询。

如果要执行多个相互依赖的查询,请使用第一个。连接持有某些状态,如锁、事务、编码、时区、变量……。

这里是一个改变使用时区的例子:

pool.getConnection(function(err, conn) {
    function setTimezone() {
       // set the timezone for the this connection
       conn.query("SET time_zone='+02:00'", queryData);
    }

    function queryData() {
       conn.query( /* some query */, queryData);
    }


    function restoreTimezoneToUTC() {
       // restore the timezone to UTC (or what ever you use as default)
       // otherwise this one connection would use +02 for future request
       // if it is reused in a future `getConnection`
       conn.query("SET time_zone='+00:00'", releseQuery);
    }

    function releaseQuery() {
        // return the query back to the pool
        conn.release()
    }

    setTimezone();
});

【讨论】:

    【解决方案2】:

    万一其他人偶然发现:

    当您使用 pool.query 时,您实际上是在调用一个快捷方式,该快捷方式执行第一个示例的操作。

    来自readme

    这是 pool.getConnection() -> connection.query() -> connection.release() 代码流的快捷方式。使用 pool.getConnection() 对于为后续查询共享连接状态很有用。这是因为对 pool.query() 的两次调用可能会使用两个不同的连接并并行运行。

    所以是的,第二个也是调用 connection.release() 你只是不需要输入它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      相关资源
      最近更新 更多