This commit is contained in:
艾贤凌
2026-03-16 12:05:55 +08:00
parent af3a7c83e8
commit 6d4a72161f
33 changed files with 5671 additions and 178 deletions

View File

@@ -7,18 +7,29 @@ const pool = mysql.createPool({
port: config.mysql.port,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database,
connectionLimit: 10,
queryFormat: function (sql, values) {
const opts = { sql, values }
this._resolveNamedPlaceholders(opts)
log4js.mysql.debug(opts.sql, opts.values)
return mysql.format(
opts.sql,
opts.values,
this.config.stringifyObjects,
this.config.timezone
)
}
// 不在启动时立即建立连接,等第一次查询时再连接
waitForConnections: true,
enableKeepAlive: true,
keepAliveInitialDelay: 10000,
});
export default pool.promise();
// 监听连接错误,避免未处理的 Promise rejection 导致进程崩溃
pool.on('connection', (connection) => {
log4js.mysql.info(`MySQL 连接建立 [id=${connection.threadId}] ${config.mysql.host}:${config.mysql.port}`);
});
pool.on('error', (err) => {
log4js.mysql.error('MySQL 连接池错误:', err.message);
});
const promisePool = pool.promise();
// 健康检查:启动时 ping 一次数据库,失败只警告不崩溃
promisePool.query('SELECT 1').then(() => {
log4js.mysql.info(`MySQL 连接成功 ${config.mysql.host}:${config.mysql.port}/${config.mysql.database}`);
}).catch((err) => {
log4js.mysql.warn(`MySQL 连接失败(服务仍将继续运行): ${err.message}`);
});
export default promisePool;