我有一个用Node 6.10编写的lambda函数,该函数连接到oracle db。我正在使用oracledb模块。由于到oracle db的连接需要10秒钟以上,因此我想在lambda的多次执行中重用连接对象。
worker.js
const os = require('os');
var fs = require('fs');
const str_host = os.hostname() + ' localhost\n';
var oracledb;
var connection;
var properties;
fs.appendFile(process.env.HOSTALIASES,str_host , function(err){
if(err) throw err;
});
try {
if (typeof oracledb === 'undefined' || oracledb === null ) {
oracledb = require('oracledb');
console.log( 'Oracle DB is supported');
if(typeof connection === 'undefined' || connection === null) {
console.log("Getting a new connection");
getDBConnection(properties, oracledb, function(err,conn) {
if(err) {
callback(err);
} else {
console.log("Setting connection object");
connection = conn;
callback();
}
});
}
}
} catch(dbError) {
console.log('Failed to load oracledb:');
console.log(dbError);
}
function getDBConnection(properties, oracledb, callback) {
var dbProperties = {
user : properties[DB_USER],
password : properties[DB_PASSWORD],
connectString : properties[DB_CONNECTION_STRING]
};
try {
if (typeof oracledb !== 'undefined' && oracledb !== null ) {
oracledb.getConnection(dbProperties)
.then( conn => {
console.log("After getting connection" + conn);
return callback(null, conn);
})
.catch(err => {
console.log("Error getting connection" + err);
return callback(err, null);
});
} else {
console.log("oracledb is undefined");
}
} catch (e) {
console.log('Failed to connect oracledb');
console.log(e);
return callback(e, null);
}
}
exports.handler = function(event, context, callback) {
console.log('Inside worker');
console.log(context);
context.callbackWaitsForEmptyEventLoop = false;
work();
});
处理程序的执行不会等到收到来自oracleDB的连接。另外请注意,在getDbConnection方法中,
oracledb.getConnection(options)返回一个Promise,然后有一个then和catch来确保连接已解决。但是在初始化连接对象之前,我仍然可以执行工作方法。
答案 0 :(得分:0)
为了解决这个问题,我做了以下工作,并且lambda只要可以保留上下文,就可以将oracleDB连接重新用于后续调用。
更改被移动,try catch块将初始化exports.handler中的连接。处理lamdba的起点。并将连接变量定义为全局变量。
var connection;
var oracledb;
exports.handler = function(event, context, callback) {
console.log('Inside worker');
console.log(context);
context.callbackWaitsForEmptyEventLoop = false;
try {
if (typeof oracledb === 'undefined' || oracledb === null ) {
oracledb = require('oracledb');
console.log( 'Oracle DB is supported');
if(typeof connection === 'undefined' || connection === null) {
console.log("Getting a new connection");
getDBConnection(properties, oracledb, function(err,conn) {
if(err) {
callback(err);
} else {
console.log("Setting connection object");
connection = conn;
callback();
}
});
}
}
} catch(dbError) {
console.log('Failed to load oracledb:');
console.log(dbError);
}
work();
});
我对此实施并不完全满意。还有其他解决方案吗?