【发布时间】:2019-10-08 00:09:18
【问题描述】:
我正在尝试为 AWS Lambda 重用 mongodb 连接,这是我的连接函数:
const openMongodbConnection = ({ config }) => (
process.mongoConnection ? Promise.resolve() : mongoose.connect(config.MONGO_URL, {
bufferCommands: false,
bufferMaxEntries: 0,
keepAlive: true,
})
.then((connection) => {
process.mongoConnection = connection;
return Promise.resolve();
}, err => (
Promise.reject({
statusCode: 500,
errorCode: [{
code: 'DatabaseError',
description: `unable to connect to mongo db: ${err} ${JSON.stringify(config)}`,
}],
})
))
);
数据库位于 AWS VPC 内,没有外部访问权限。 冷启动完美运行,但有时我会收到这样的超时错误:
2018-10-03T18:36:06.984Z 7ab97df7-c739-11e8-89bf-87260b172585 MongoNetworkError: connection 2 to some.ip.from.server:27017 timed out
at Socket.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/connection.js:258:7)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
我在函数的开头也有context.callbackWaitsForEmptyEventLoop = false;。
这个错误是完全随机的,有时有效,有时无效,我正在考虑每次出现新请求时打开和关闭连接,但我知道这会降低 lambdas 的性能,也会增加 I来自 mongodb 服务器的 /O 操作。
我们将不胜感激。
【问题讨论】:
标签: node.js amazon-web-services mongoose aws-lambda