AWS Lambda部署node-mysql遇ER_CON_COUNT_ERROR:连接数过多问题排查
我使用如下配置构建node-mysql项目:
db.js
const mysql = require("mysql"); const config = require("../core/config/config.json"); const db = mysql.createPool({ host: config.mysql.host, port: config.mysql.port, user: config.mysql.user, password: config.mysql.password }); db.getConnection((err, connection) => { if (err) { console.error(err); return; } connection.ping(); connection.release(); console.log("Database connected !"); }); module.exports = db;
同时存在多个查询文件,示例如下:
query1.js
const mysql = require("../db"); mysql.query("select * from table", [param], (error, results) => { if (error) { return cb(error); } return cb(null, results); });
query2.js、query3.js等文件结构与上述一致。
本地运行时一切正常,但将代码部署到AWS Lambda函数后,出现错误:
ER_CON_COUNT_ERROR: Too many connections error in node-mysql
请问我哪里操作有误?如何通过当前配置避免该错误?
核心问题
AWS Lambda会复用执行容器,每次触发时若有闲置容器会直接复用。你的db.js在模块加载阶段就调用db.getConnection(),且未配置连接池最大连接数,随着Lambda触发次数增加,容器复用过程中会不断创建新连接,最终超出MySQL的最大连接数限制,导致报错。
修正步骤
移除模块加载时的冗余连接测试
删除db.js中这段无意义的连接测试代码:db.getConnection((err, connection) => { if (err) { console.error(err); return; } connection.ping(); connection.release(); console.log("Database connected !"); });这段代码在模块加载时就创建并释放连接,会在Lambda容器复用过程中不断产生额外连接请求,加剧连接数占用。
配置连接池的限制参数
在createPool中添加连接池控制参数,避免无限制创建连接:const db = mysql.createPool({ host: config.mysql.host, port: config.mysql.port, user: config.mysql.user, password: config.mysql.password, connectionLimit: 10, // 控制连接池最大连接数,根据MySQL的max_connections调整,Lambda场景建议设小 waitForConnections: true, // 连接数满时等待而非直接报错 queueLimit: 0 // 无限等待队列(可根据业务需求调整) });添加连接超时配置
配置闲置连接自动回收,避免长期占用MySQL资源:const db = mysql.createPool({ // ... 原有配置 acquireTimeout: 60000, // 获取连接超时时间(毫秒) idleTimeout: 30000 // 连接闲置超时时间(毫秒) });确保连接正确释放(事务场景注意)
若后续使用手动获取连接的场景(如事务),必须在回调中调用connection.release()或connection.destroy(),避免连接泄漏。当前使用mysql.query()会自动管理连接,无需修改,但需留意后续场景。
补充说明
Lambda执行容器可能被复用数分钟,配置闲置超时后,连接池会自动销毁闲置连接,减少资源占用。调整connectionLimit时,要确保所有Lambda实例的连接数总和不超过MySQL的max_connections参数(默认100)。
内容的提问来源于stack exchange,提问作者micronyks

