import mysql from "mysql2"; import config from "../config/index.js"; import * as log4js from "../log4js.js"; const pool = mysql.createPool({ host: config.mysql.host, port: config.mysql.port, user: config.mysql.user, password: config.mysql.password, database: config.mysql.database, connectionLimit: 10, // 不在启动时立即建立连接,等第一次查询时再连接 waitForConnections: true, enableKeepAlive: true, keepAliveInitialDelay: 10000, }); // 监听连接错误,避免未处理的 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;