使用mysql模块创建连接池,出现链接不释放,卡死的问题

项目中用的Express,用了express-myconnection中间件创建连接池,连接限制数量为10。在运行过程中发现若链接数量超过限制,就直接卡死,无论等待多久也无法进行新的查询,也不报错,再次获取链接。
出现这个问题的原因肯定是由于已创建的链接没有进行释放。然而这个看了中间件的源码,也只是对mysql模块进行的简单封装,调用的也是mysql.createPool
于是我想知道这个情况到底是我代码的问题,还是mysql模块自身的问题,各位大神赐教!

运行代码

 exports.index = function(req, res) {
    console.log('start');
    req.getConnection(function(err,con){
        console.log('got connection');
        if(err){
            res.end('err');
        }
        var sql='select id from integrated_db.community'
        con.query(sql,[],function(err,data){
            res.end('data');
        });
    });
}

控制台 多次刷新页面,会持续输出:

> start 
> got connection 
> start 
> got connection
> start got
> connection
> start
> got connection

控制台 当刷新次数多了之后,就只会出现:

> start
> got connection
> start
> start
> start
> start
> start

后面就一直卡死了,不会有新的链接能够进行了。
求指教。

阅读 3.3k
2 个回答

我找到连接池卡死的原因啦!说一下,如果有哪位同学也在用express-myconnection模块的话可以改一改。

问题原因: express-myconnection模块对链接释放存在缺陷。
解决方法:(原文)https://github.com/pwalczyszy...
具体操作: 修改一下它释放链接的方法就可以啦~ 步骤如下

// 原关闭连接方法
    var end = res.end;
    res.end = function (data, encoding) {
        console.log('end2');
        // Ending request connection if available
        if (requestConnection) requestConnection.end();

        // Releasing pool connection if available
        if (poolConnection) poolConnection.release();

        res.end = end;
        res.end(data, encoding);
    }

修正版:

// Request terminanted unexpectedly.
    res.on("close", function () {
        // Ending request connection if available
        if (requestConnection) requestConnection.end();

        // Releasing pool connection if available
        if (poolConnection) poolConnection.release();

        console.log('close1');
    });
    // Normal response flow.
    res.on("finish", function () {
        // Ending request connection if available
        if (requestConnection) requestConnection.end();

        // Releasing pool connection if available
        if (poolConnection) poolConnection.release();

        console.log('finish1');
    });

测试没发现你说的问题 再贴出些代码看看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题