【问题标题】:knexjs promise release pool connectionknexjs 承诺释放池连接
【发布时间】:2017-05-26 02:29:28
【问题描述】:

我目前使用knexjs.org,承诺代替常规回调,并使用池连接进行 SQL 查询。第一次,它运行平稳。但现在我通常会面临池连接错误。代码是这样的

knex('user_detail')
                .select('id','full_name','phone','email')
                .where('id', id_user)
                .then((result) => {
                    resolve(result);
                })
                .catch((error) => {
                    reject(error);
                })

但现在我通常会收到错误连接超时和错误池连接。首先为什么会出错可能是因为我没有释放连接,但是我有这样的代码,

knex('user_detail')
                .select('id','full_name','phone','email')
                .where('id', id_user)
                .then((result) => {
                    resolve(result);
                })
                .catch((error) => {
                    reject(error);
                })
                .finally(() => {
                    knex.destroy()
                })

它在第一次尝试时有效,但在第二次尝试时失败并收到错误There is no pool defined on the current client,有时还会出现错误The pool is probably full

有人可以向我解释发生了什么以及我如何解决它吗?谢谢。

【问题讨论】:

    标签: mysql node.js promise connection-pooling knex.js


    【解决方案1】:

    没有足够的信息来说明您为什么首先会用完池连接。

    你调用一些 resolve()reject() 函数的方式给人一种预感,即你使用 Promise 效率低下或完全错误......

    如果您添加完整的代码示例,您将如何获得 the pool is probably full 错误,我可以编辑答案并提供更多帮助。例如,通过意外创建多个未解决的交易,池将填满。

    在第二个代码示例中,您调用 knex.destroy() 不会破坏单个池连接,但会完全破坏 knex 实例和您正在使用的池。

    所以在knex.destroy() 之后,您将无法再使用该knex 实例,您必须通过再次提供数据库连接配置来创建全新的实例。

    【讨论】:

      【解决方案2】:

      这样你就不需要处理连接了,它会在返回时自动提交+释放到池中,在抛出错误时回滚。

      const resultsAfterTransactionIsComplete = await knex.transaction(async trx => {
        const result = await trx('insert-table').insert(req.list).returning('*');
      
        // insert logs in the same transaction
        const logEntries = result.map(o=> ({event_id: 1, resource: o.id}));
        await trx('log-table').insert(logEntries);
      
        // returning from transaction handler automatically commits and frees connection back to the pool
        return results; 
      });
      

      【讨论】:

        猜你喜欢
        • 2014-08-06
        • 2013-05-01
        • 2016-10-24
        • 2012-04-22
        • 1970-01-01
        • 2015-12-04
        • 2015-07-29
        • 1970-01-01
        • 2017-05-06
        相关资源
        最近更新 更多