mysql - Node : Heroku ClearDB not closing connections

标签 mysql node.js heroku cleardb

我在 Heroku 上部署了一个 NodeJS API 并尝试将它连接到一个 MySQL 数据库,因此我创建了一个连接池来处理 ClearDB ignite 帐户(免费)上的连接,它最多允许 10 个连接。

每次我对数据库执行查询时,它只会向堆栈添加一个新连接,直到达到 10 个连接并且应用程序崩溃。

我的代码如下:

连接工厂:

var mysql = require('mysql');

function createDBConnection() {
    var conn = mysql.createPool({
      host: 'xxx',
      user: 'xxx',
      password: 'xxx',
      database: 'xxx'
    });
    return conn;
}

module.exports = function() {
  return createDBConnection;
}

这是我的选择查询:

function Dao(connection) {
  this._connection = connection;
}

Dao.prototype.findAll = function (callback) {
  this._connection.query('SELECT * FROM table',
  function(errors, results) {
    callback(errors,results);
  });
};

module.exports = function() {
  return Dao;
}

最后这是我用来调用它的路由:

app.get('/products', function (req,res) {
    var connection = app.persistence.connectionFactory();
    var dao = new app.persistence.Dao(connection);

    dao.findAll(function (err, result) {
      res.format({
        json: function () {
          res.json(result);
        }
      });
    });
  });

我尝试将 createPool() 更改为 createConnection(),然后在每次查询后立即调用 .end()/.destroy() 函数,但它根本不起作用。

有什么提示吗?

最佳答案

为了关闭连接/将连接返回到池中,请使用:connection.release()

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

pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query('SELECT something FROM sometable', function (error, results, fields) {
    // And done with the connection.
    connection.release();

    // Handle error after the release.
    if (error) throw error;

    // Don't use the connection here, it has been returned to the pool.
  });
});

mysql : Pooling connections Documentation

关于mysql - Node : Heroku ClearDB not closing connections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46015250/

相关文章:

MySQL int 列映射到 Int64。我怎样才能让它映射到Int32(即int)?

php - 如何在服务器中导入一个大的SQL文件?

mysql - 似乎无法找到 mysql 数据库

mysql - 解密 MySQL 编码

multithreading - NodeJs 是如何处理这么多传入请求的,它使用线程池吗?

javascript - Angular 通用 - 语法错误 : Unexpected token import

ssl - Heroku SSL 主机不工作(Heroku | 没有这样的应用程序)

javascript - 收集 Api 返回的数组

python - 如何为 Python 使用 Heroku buildpack ffmpeg?

ruby-on-rails - 如何在主域上托管 WordPress 站点,在子域上托管 Rails 站点