我制作了包含一些REST服务的node.js应用程序。这些服务连接到数据库(例如Oracle或DB2)以执行某些查询。
由于我是node.js编程的初学者,我对我的案例有疑问: 访问数据库的正确方法是什么?在应用程序运行时有一个连接引用是否更好,并在调用REST服务时使用相同的连接实例?
我在一个单独的模块中找到了一些包含数据库连接的示例,并在app中使用该模块,如下所示:
db2.js:
var db2 = require('ibm_db');
var db2ConnSettings = "DRIVER={DB2};DATABASE=mydb;HOSTNAME=localhost;UID=db2test;PWD=db2test;PORT=50000;PROTOCOL=TCPIP";
var db2Conn = db2.open(db2ConnSettings, function(err, conn) {
if (err)
return console.log(err);
});
module.exports = db2Conn;
server.js:
var express = require('express');
var app = express();
var db2Connection = require('./db2.js');
app.get('/data', function(req, res) {
console.log(db2Connection );
// make some query
});
调用此服务时,db2connection
为undefined
。怎么会?我该如何从db2.js
文件中检索db2连接?
答案 0 :(得分:2)
正如@Sirko所说:
var db2 = require('ibm_db');
var db2ConnSettings = "DRIVER={DB2};DATABASE=mydb;HOSTNAME=localhost;UID=db2test;PWD=db2test;PORT=50000;PROTOCOL=TCPIP";
var err, conn;
var callbacks = [];
module.exports = function(callback) {
// db2 module is called
if (err || conn) {
// connection has already been established
// (results of db2.open have been stored)
// callback immediately
callback(err, conn);
}
else {
// connection has not been established
// store the callback for when db connects
callbacks.push(callback);
}
};
db2.open(db2ConnSettings, function(_err, _conn){
// db has connected
err = _err; conn = _conn; // store results
var next_callback;
// array.pop() removed the last item from the array
// and returns it. if no items are left, returns null.
// so this loops through all stored callbacks.
while(next_callback = callbacks.pop()) {
// the removed item is stored in next_callback
next_callback(err, conn); // send connection results to callback
}
// no more items in callbacks to trigger
});
var express = require('express');
var app = express();
var db2Connection = require('./db2.js')(function(err, conn) {
// triggered if the connection has already been established
// or as soon as it HAS been established
app.get('/data', function(req, res) {
console.log(conn);
// ...
});
});
答案 1 :(得分:2)
对于Oracle with node-oracledb,创建和使用连接池很简单。只要处理HTTP REST请求,您的应用程序就可以从池中获得免费连接。查看examples中的webapp.js
和webapppromises.js
。 Node-oracledb有一个“连接池队列”(参见doc),它处理连接负载峰值。它还有一个“连接池缓存”(也见文档),可以轻松访问在不同模块中创建的池。