我正在创建一个使用 Node.js 和 Express 的 RESTful API。我的应用程序使用 Oracle 数据库,所以我从 npm 安装了 node-oracledb 模块。我查看了文档并查看了模块的 github 页面中提供的一些示例;但是,我没有看到任何使用连接池的示例。如果我错了,请纠正我,但对于将对数据库进行多次调用的应用程序,建议使用连接池而不是使用独立连接。以下是我编写的代码示例:
createPool = function(poolAttrs, fetchPool){
oracledb.createPool(poolAttrs, function(error, pool){
if(error){
console.error(`Could not create pool using specified attributes: `, error.message);
}
else{
console.log(`Pool created successfully using poolAlias: ${poolAttrs.poolAlias}`);
fetchPool(pool);
}
});
};
createConnection = function(poolAlias, connection){
oracledb.getConnection(poolAlias, function(error, conn){
if(error){
console.error(`Could not get connection: `, error.message);
} else {
console.log(`New connection obtained: ${conn}`);
connection(conn);
}
});
};
executeQuery = function(queryString, poolAlias){
console.log(queryString);
var conn = createConnection(poolAlias, function connection(conn){
conn.execute(queryString, function(error, result){
if(error){
console.error(`Could not execute query: `, error.message);
} else {
console.log(result);
}
conn.close(function(error){
if(error){
console.error(`Could not close connection.`);
} else {
console.log(`Connection successfully closed.`);
}
})
});
});
}
closePool = function(pool){
pool.close(60, function(error){
if(error){
console.error(`Could not close connection pool ${pool.poolAlias}`, error.message);
} else {
console.log(`Pool closed successfully.`);
}
});
};
createPool(attrs, function fetchPool(pool){
var poolAlias = pool.poolAlias;
console.log(poolAlias);
});
executeQuery(queryString, attrs.poolAlias);
当我运行这段代码时,出现以下错误:
Could not get connection: NJS-047: poolAlias "amDBpool" not found in the connection pool cache
我知道错误发生的原因。随着我对回调的理解,我知道使用 fetchPool(pool) 回调调用异步 createPool() 函数会在回调堆栈中注册此回调 (fetchPool)。所有同步代码都将在它之前执行。因此,当我调用 executeQuery 并且该函数到达调用 createConnection(poolAlias...) 的执行行时,poolAlias 变量为 null,因为 createPool 函数仍在回调堆栈中等待执行。因此,不存在别名为“poolAlias”的池,调用失败。我知道我可以将对 createPool 的调用保留在 executeQuery 方法中,但这不会在我每次执行查询时尝试创建一个新池吗?我的问题是,有没有一种方法可以在池存在的 executeQuery 方法中进行测试,如果不存在则不尝试重新创建它。除此之外,唯一的其他方法是使用 Promises 或 Async/Await,对吧?
最佳答案
使用连接池的 node-oracledb 示例是 connectionpool.js和 examples/webap.js
文件。是的,连接池在 Web 服务中是个好主意。我还建议使用异步/等待编程风格。
您可以看到示例在执行任何其他操作之前创建了一个连接池:
await oracledb.createPool({
user: dbConfig.user,
password: dbConfig.password,
connectString: dbConfig.connectString
});
从 oracledb.createPool()
调用返回的池被忽略,因为池稍后通过 pool cache 访问因为没有凭证传递给 getConnection()
:
let connection = await oracledb.getConnection();
这使用默认池别名(恰好是字符串“default”),因此在创建或使用池时没有指定别名。
关于使用 node-oracledb 连接池的文档和提示在 Connection Pooling 中.
您可能对 Creating a REST API with Node.js and Oracle Database 感兴趣, A node-oracledb Web Service in Docker和 Demo: GraphQL with Oracle Database and node-oracledb
关于javascript - 调用 node-oracledb 的 createPool 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384255/