使用单例模式,数据库线程池,网上找的一些不是很好用,就自己简单写了一个,方便后期使用
const mysql = require('mysql'); //导入mysql中间件
const lodash = require('lodash');
// 默认配置文件
var defaultConfig= require('@/config/mysql.js');
class DB {
// 多次连接共享实例对象
static getInstance () {
if (!DB.instance) {
DB.instance = new DB();
};
// 简化性能提升
return DB.instance;
}
//默认初始化执行方法
constructor() {
// 存放mysql连接后的对象
this.pool = "";
this.dbClient = "";
this.config = defaultConfig
};
// 修改数据库链接配置
setConfig (conf) {
// merge 和 assign 区别在于assign 只能合并第一层,merge 可以递归合并多层,具体查看lodash官方文档
this.config = lodash.merge(this.config, conf);
// 初始化连接数据库
this.connect()
}
//1.建立连接
connect () {
const that = this
return new Promise((