1
0
Code Issues Pull Requests Projects Releases Wiki Activity GitHub Gitee
tools/utils/dbPoolUtils.js

82 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const mysql = require('mysql');
const fs = require('fs');
const path = require('path');
let globalConfig = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json'), 'utf8'));
let pool = null;
function create({ database, connectionLimit = 10 }) {
let config = {
connectionLimit: connectionLimit, //连接数量默认是10
...globalConfig[global.dbConfig || 'mysql'],
database: database,
};
// console.log(config);
//创建数据库连接池
pool = mysql.createPool(config);
// //从连接池中获取连接时,将触发该事件
// pool.on('acquire', function (conn) {
// console.log('获取连接', conn.threadId);
// });
//在连接池中建立新连接时,将触发该事件
pool.on('connection', function (conn) {
console.log('建立新连接', conn.threadId);
});
// //等待可用连接时,将触发该事件
// pool.on('enqueue', function () {
// console.log('等待可用连接');
// });
// //当连接释放回池中时,触发该事件
// pool.on('release', function (conn) {
// console.log('连接被释放回池中', conn.threadId);
// });
}
async function query(sql, params) {
return await new Promise(function (resolve, reject) {
if (!pool) {
console.error('Database connection pool is not initialized yet.');
resolve(data);
return;
}
// pool.query()方法可以自动的帮我们在连接池中获取可用连接
pool.query(sql, params, function (err, data) {
if (err) reject(err);
resolve(data);
});
// // 当然我们也可以手动获取可用连接
// pool.getConnection(function (err, conn) {
// if (err) reject(err);
// conn.query(sql, function (err, data) {
// if (err) reject(err);
// resolve(data);
// // 连接用完之后,需要释放,重新放回连接池中。
// // 注意这里并没有销毁该连接,该连接仍然可用,但需要重新获取
// conn.release();
// });
// });
});
}
async function close() {
await new Promise((resolve, reject) => {
if (!pool) return;
pool.end(function (err) {
console.log('关闭连接池', err);
resolve(err);
});
});
}
module.exports = {
create: create,
query: query,
close: close,
}