我正在使用node-mssql创建一个连接到sql server的应用程序,并且试图为整个应用程序使用连接池以提高性能。我为此创建了一个单例课程
export class MSSQLHelper {
connectionPool = null;
helperInstance = null;
constructor() {
this.connectionPool = null;
}
static getMSSQLHelperInstance(){
if(!this.helperInstance) {
this.helperInstance = new MSSQLHelper();
}
return this.helperInstance;
}
getConnectionPool() {
let deferred = Q.defer();
let { reject, resolve, promise } = deferred;
if(this.connectionPool) {
if(this.connectionPool._connected && !this.connectionPool._connecting) {
resolve(this.connectionPool);
}
else {
this.connectionPool.connect(err => {
if(err) {
reject(err);
}
else{
resolve(this.connectionPool);
}
})
}
}
else {
logger.debug("start of creating connection pool");
let pool = new sql.ConnectionPool(dbSetting, err => {
logger.debug("end of creating conneciton pool");
if (err) {
reject(err);
if(close in pool){
pool.close();
this.connectionPool = null;
}
}
else {
this.connectionPool = pool;
resolve(pool);
}
});
}
return promise;
}
}
每次我尝试访问数据库时,我都会调用getConnectionPool来获取池。但是,当我尝试测试某些意外关闭池的极端情况时。上面的代码不起作用。 似乎池有几种状态。他们是:
由于我程序中的多个位置调用sql来记录某些内容,因此在相似的时间可能会有多个方法调用getConnectionPool()。对于意外关闭池后的第一个sql查询,调用this.connection.connect应该可以,但是对于其他后续方法调用,由于正在分配新的连接池,因此将返回错误。 我们遇到了类似数据库已在连接和ESOCKET错误的错误。 因此,我不确定这是否是使用连接池的正确方法。如何确保连接池关闭后就可以连接并且以后的所有SQL查询都正常?如果_connecting为true,我是否应该setTimeout暂停方法cll一段时间,然后稍后再次检查_connecting的值以确保在该SQL查询发生之前建立池?
谢谢。