【发布时间】:2018-01-24 03:17:15
【问题描述】:
所以我按照https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs 的示例来优化我的 lambda 函数。
我尝试了两种方法,并在本地使用 serverless-offline 对其进行了测试,但似乎都不起作用。
第一种方法
// endpoint file
import {connectToDatabase} from "lib/dbUtils.js";
let cachedDb = null;
export function post(event, context, callback) {
let response;
context.callbackWaitsForEmptyEventLoop = false;
connectToDatabase()
.then(//do other stuff
// lib/dbUtils.js
export async function connectToDatabase() {
if (cachedDb && cachedDb.serverConfig.isConnected()) {
console.log(" using cached db instance");
return cachedDb;
}
cachedDb = await mongoose.createConnection(
process.env.DB_URL,
async err => {
if (err) {
throw err;
}
}
);
return cachedDb;
}
第二种方法
global.cachedDb = null;
export function post(event, context, callback) {
let response;
context.callbackWaitsForEmptyEventLoop = false;
connectToDatabase()
.then(connection => createUser(event.body, connection))
// lib/dbUtils.js
export async function connectToDatabase() {
// eslint-disable-next-line
if (global.cachedDb && global.cachedDb.serverConfig.isConnected()) {
// eslint-disable-next-line
console.log(" using cached db instance");
// eslint-disable-next-line
return global.cachedDb;
}
// eslint-disable-next-line
global.cachedDb = await mongoose.createConnection(
process.env.DB_URL,
async err => {
if (err) {
throw err;
}
}
);
// eslint-disable-next-line
return global.cachedDb;
}
在这两种情况下,using cached db instance 控制台日志都不会运行。
为什么这不起作用?这是因为 serverless-offline 的原因吗?
【问题讨论】:
-
先在AWS上试用,再评论
-
您正在尝试的是完全合法的——不能保证容器会被重用,但很有可能会被重用。我不明白为什么你似乎让这个测试用例变得比它需要的复杂得多。这可能是范围界定问题吗?将所有这些代码放在一个文件中,使其工作,然后将其拆分为不同的文件。您正在测试两个条件
if (cachedDb && cachedDb.serverConfig.isConnected())但您没有记录第一个条件以查看它是否为真。
标签: node.js mongodb amazon-web-services aws-lambda serverless