我有一个使用 mongoose 查询 mongoDb 的节点 lambda 函数。
大约 20% 的时间,看似随机,我在尝试连接时收到以下错误: MongoNetworkTimeoutError:连接超时
虽然 MongoDb 似乎建议使用 context.callbackWaitsForEmptyEventLoop = false 并尝试在调用之间重用相同的连接,但我阅读了其他帖子,说解决此问题的方法是每次都主动重新打开连接。我试过了,但它仍然发生。有人有什么想法吗?
这是我的代码:
let conn = mongoose.createConnection(process.env.MONGO_URI, {
bufferCommands: false, // Disable mongoose buffering
bufferMaxEntries: 0, // and MongoDB driver buffering
useNewUrlParser: true,
useUnifiedTopology: true,
socketTimeoutMS: 45000,
keepAlive: true,
reconnectTries: 10
})
try {
await conn
console.log('Connected correctly to server')
} catch (err) {
console.log('Error connecting to DB')
console.log(err)
console.log(err.stack)
}
await conn
这里是 Cloudwatch 的完整错误输出:
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "MongoNetworkTimeoutError: connection timed out",
"reason": {
"errorType": "MongoNetworkTimeoutError",
"errorMessage": "connection timed out",
"name": "MongoNetworkTimeoutError",
"stack": [
"MongoNetworkTimeoutError: connection timed out",
" at connectionFailureError (/var/task/node_modules/mongodb/lib/core/connection/connect.js:342:14)",
" at TLSSocket.<anonymous> (/var/task/node_modules/mongodb/lib/core/connection/connect.js:310:16)",
" at Object.onceWrapper (events.js:420:28)",
" at TLSSocket.emit (events.js:314:20)",
" at TLSSocket.EventEmitter.emit (domain.js:483:12)",
" at TLSSocket.Socket._onTimeout (net.js:484:8)",
" at listOnTimeout (internal/timers.js:554:17)",
" at processTimers (internal/timers.js:497:7)"
]
},
"promise": {},
"stack": [
"Runtime.UnhandledPromiseRejection: MongoNetworkTimeoutError: connection timed out",
" at process.<anonymous> (/var/runtime/index.js:35:15)",
" at process.emit (events.js:326:22)",
" at process.EventEmitter.emit (domain.js:483:12)",
" at processPromiseRejections (internal/process/promises.js:209:33)",
" at processTicksAndRejections (internal/process/task_queues.js:98:32)",
" at runNextTicks (internal/process/task_queues.js:66:3)",
" at listOnTimeout (internal/timers.js:523:9)",
" at processTimers (internal/timers.js:497:7)"
]
}
答案 0 :(得分:0)
我遇到了同样的问题(我有一个 Express 应用程序,但这并不重要)。解决方案是将数据库连接对象移到处理程序方法之外并缓存/重用它。
'use strict'
const serverless = require('serverless-http')
const MongoClient = require('mongodb').MongoClient
const api = require('./modules/api')
const SecureConfig = require('./modules/secureConfig')
let dbObject = null
const getDBConnection = async (event, context) => {
try {
if (dbObject && dbObject.serverConfig.isConnected()) return dbObject
const client = await MongoClient.connect(SecureConfig.mongodb.host, SecureConfig.mongodb.mongoConfig)
dbObject = client.db(SecureConfig.mongodb.db)
return dbObject
} catch(err) {
throw(err)
}
}
module.exports.handler = async (event, context) => {
const db = await getDBConnection()
const server = serverless(api.default(db));
try {
/**
* Lambda’s context object exposes a callbackWaitsForEmptyEventLoop property,
* that effectively allows a Lambda function to return its result to the caller
* without requiring that the MongoDB database connection be closed.
* This allows the Lambda function to reuse a MongoDB connection across calls.
*/
context.callbackWaitsForEmptyEventLoop = false
return await server(event, context)
} catch (error) {
console.error('Lambda handler root error.')
throw error
}
}
您可以在此处找到更多详细信息:https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs