首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是什么导致AWS Lambda上的Mongodb超时错误?

是什么导致AWS Lambda上的Mongodb超时错误?
EN

Stack Overflow用户
提问于 2021-01-15 02:06:52
回答 1查看 749关注 0票数 4

我有一个使用mongoose查询mongoDb的node lambda函数。

大约20%的时间,似乎是随机的,我在尝试连接时得到以下错误: MongoNetworkTimeoutError: connection timed out

虽然MongoDb似乎建议使用context.callbackWaitsForEmptyEventLoop = false并尝试在调用之间重用相同的连接,但我读到其他帖子说,解决这个问题的方法是每次都主动重新打开连接。我试过了,但它仍然在发生。有谁有什么想法吗?

下面是我的代码:

代码语言:javascript
运行
复制
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的完整错误输出:

代码语言:javascript
运行
复制
{
    "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)"
    ]
}
EN

回答 1

Stack Overflow用户

发布于 2021-05-14 15:48:03

我也有同样的问题(我有一个express应用程序,但这无关紧要)。解决方案是将数据库连接对象移到处理程序方法之外,并缓存/重用它。

代码语言:javascript
运行
复制
'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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65724538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档