最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何处理Node.js中关闭的MySQL连接?

网站源码admin16浏览0评论

如何处理Node.js中关闭的MySQL连接?

如何处理Node.js中关闭的MySQL连接?

我已经建立了一个连接到MySQL数据库的Node.js API。我使用node-mysql2作为驱动程序。 API和数据库在单独的Docker容器中运行。在Kubernetes集群中部署后的某个时候,出现以下错误:

Error: Can't add new command when connection is in closed state                                                                                                                                                                                                    
    at PromiseConnection.query (/usr/src/app/node_modules/mysql2/promise.js:92:22)  

我想知道为什么会发生此错误,以及如何使用Node.js捕获并处理它。这些是我的Node.js API的代码段:

const mysql = require('mysql2/promise')
...

async function main() {
    try {
        const client = await mysql.createConnection({
            host: DATABASE_HOST,
            port: DATABASE_PORT,
            user: DATABASE_USERNAME,
            password: DATABASE_PASSWORD,
            database: DATABASE_NAME
        })

        client.on('error', error => {
            process.stderr.write(`${error.code}\n`) // PROTOCOL_CONNECTION_LOST
            process.stderr.write(`An error occurred while connecting to the db: ${error.message}\n`)
            process.exit(1)
        })

    } catch (error) {
        process.stderr.write(`Error while creating db connection: ${error.code}\n`)
    }

    ...
}

...


main().catch(err => {
  process.stderr.write(`Error message: ${err.message}\n`)
  process.exit(1)
})

您知道如何处理此错误吗?

回答如下:

完成连接后是否关闭连接?

client.end();

也考虑使用游泳池吗?

const pool = mysql.createPool({
  host: DATABASE_HOST,
  user: DATABASE_USERNAME,
  database: DATABASE_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

有关池的更多信息:https://github/sidorares/node-mysql2#using-connection-pools

发布评论

评论列表(0)

  1. 暂无评论