NodeJS + mysql - 自动关闭池连接?

Zby*_*nek 5 mysql connection-pooling node.js

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

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

pool.getConnection(function(err, conn) {
    conn.query('select 1+1', function(err, res) {
        conn.release();
    });
});
Run Code Online (Sandbox Code Playgroud)

或者我可以这样使用它:

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);
});
Run Code Online (Sandbox Code Playgroud)

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

t.n*_*ese 6

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

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

这是更改所用时区的示例:

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

Run Code Online (Sandbox Code Playgroud)


小智 5

如果其他人偶然发现这一点:

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

自述文件中:

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

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