两个问题
- 多次连接数据库
- 多次实例化
const Config = require("./config");
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });
class Db {
// 解决多次实例化,实例不共享的问题
static getInstance() {
if (!Db.instance) {
Db.instance = new Db();
}
return Db.instance;
}
constructor() {
this.dbClient = "";
this.connect(); // 第一次实例化的时候,就开始连接数据库,这样效率更高
}
connect() {
return new Promise((resolve, reject) => {
// 把数据库的连接变成长连接,解决多次连接数据库的操作
if (this.dbClient) {
resolve(this.dbClient);
} else {
client.connect(err => {
if (err) {
reject(err);
} else {
this.dbClient = client.db(Config.dbName);
resolve(this.dbClient);
}
});
}
});
}
find(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const collection = db.collection(collectionName);
collection.find(json).toArray((err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
})
.catch(err => {
reject(err);
});
});
}
}
const db = Db.getInstance();
// const db = new Db();
console.time("db1");
db.find("student", {})
.then(docs => {
console.timeEnd("db1");
})
.catch(e => {
console.log(e.message);
});
setTimeout(() => {
console.time("db2");
db.find("student", {})
.then(docs => {
console.timeEnd("db2");
})
.catch(e => {
console.log(e.message);
});
}, 3000);
const db1 = Db.getInstance();
// const db1 = new Db();
setTimeout(() => {
console.time("db3");
db1
.find("student", {})
.then(docs => {
console.timeEnd("db3");
})
.catch(e => {
console.log(e.message);
});
}, 5000);
setTimeout(() => {
console.time("db4");
db1
.find("student", {})
.then(docs => {
console.timeEnd("db4");
})
.catch(e => {
console.log(e.message);
});
}, 7000);
网友评论