【问题标题】:Application does not terminate with MySQL pool应用程序不会以 MySQL 池终止
【发布时间】:2013-05-20 10:55:28
【问题描述】:

我正在编写一个 nodejs 应用程序并想使用连接池。

但是,以下应用程序不会终止 - 尽管我希望它在调用 connection.end() 后终止

如果我使用一个连接而不是池,应用程序就可以正常工作。我需要以某种方式终止池吗?

使用的库https://github.com/felixge/node-mysql
node.js 版本:在 Ubuntu 上为 0.10.4

var mysql      = require('mysql');
var pool = mysql.createPool({
    host     : 'example.org',
    user     : 'myuser',
    password : 'youbet',
    database : 'notrevealingdetails',
    insecureAuth: true
});

function getCampaignData(callback)
{
    pool.getConnection(function(err, connection) {
        if(err) throw err;

        connection.query(
            'SELECT cam.id, cam.name AS campaign_name, cam.subdomain, usr.email, usr.display_name AS user_displayname ' +
            'FROM campaigns AS cam INNER JOIN users AS usr ON usr.id = cam.user_id ' +
            'WHERE cam.state=2',
            function(err, rows) {
                callback(err, rows,connection);
                //console.log('called end()');
        }); // callback function for connection.query
    }); // end pool.GetConnection
}

getCampaignData(function(err, rows, connection) {
    if (err) throw err;


    connection.end();
    console.log("I expect my app to terminate");
});

【问题讨论】:

  • 尝试使用 connection.destroy() 代替
  • @spotirca connection.destroy() 将(根据文档)终止连接。如果我这样做,那么首先使用游泳池就没有意义了——对吧? (但它有效
  • “它有效”我的意思是:应用程序终止。我仍然想要一种让游泳池工作的方法

标签: mysql node.js node-mysql


【解决方案1】:

我遇到了同样的问题,但是查看源代码 https://github.com/felixge/node-mysql/blob/master/lib/Pool.js 我发现池,至少在它当前的实现中,有一个 end() 方法,它在所有连接上轮流调用 end()。

它还接受在所有连接实际结束后(或发生错误时)调用的回调函数。

pool.end(function (err) {
    if (err) console.error("An error occurred: " + err);
    else console.log("My app terminated");
});

【讨论】:

    【解决方案2】:

    我会用

    getCampaignData(function(err, rows, connection)
    {
        if (err) throw err;
        connection.release();
        console.log("I expect my app to terminate");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 2021-07-08
      相关资源
      最近更新 更多