feat: mysql和redis连接

This commit is contained in:
luozhj33 2026-03-19 14:04:35 +08:00
parent cbda32bdb0
commit a6e6a13614

53
back/src/config/mysql.js Normal file
View File

@ -0,0 +1,53 @@
const mysql = require('mysql2/promise');
// 从环境变量读取配置,支持默认值 // TODO
const MYSQL_HOST = '127.0.0.1';
const MYSQL_PORT = 3306;
const MYSQL_USER = 'root';
const MYSQL_PASSWORD = '123456';
const MYSQL_DATABASE = 'cus';
// 创建连接池
const pool = mysql.createPool({
host: MYSQL_HOST,
port: MYSQL_PORT,
user: MYSQL_USER,
password: MYSQL_PASSWORD,
database: MYSQL_DATABASE,
waitForConnections: true,
connectionLimit: 10, // TODO
queueLimit: 0
});
// 测试连接 // TODO
pool.getConnection()
.then((connection) => {
console.log('MySQL 连接成功'); // TODO
connection.release();
})
.catch((err) => {
console.error('MySQL 连接失败:', err); // TODO
});
// 执行查询
async function query(sql, params) {
const [rows] = await pool.execute(sql, params);
return rows;
}
// 获取连接
async function getConnection() {
return pool.getConnection();
}
// 关闭连接池
async function close() {
return pool.end();
}
// 导出方法
module.exports = {
query,
getConnection,
close
};