node.js - AWS Lambda(Node.js,8.10 版)和 Mongoose : MongoNetworkError connection to DB timed out

标签 node.js mongodb mongoose aws-lambda serverless

环境:

  • AWS Lambda(Node.js,8.10 版),waitForEmptyEventLoop === false
  • MongoDB(图集)
  • Mongoose

问题:有时(随机)我得到下一个错误:

MongoNetworkError: connection 6 to db_host:27017 timed out
  File "/opt/nodejs/node_modules/mongodb-core/lib/connection/connection.js", line 259, col 7, in TLSSocket.<anonymous>
    new MongoNetworkError(f('connection %s to %s:%s timed out', self.id, self.host, self.port)),
  File "events.js", line 313, col 30, in Object.onceWrapper
  File "events.js", line 106, col 13, in emitNone
  File "events.js", line 208, col 7, in TLSSocket.emit
  File "net.js", line 420, col 8, in TLSSocket.Socket._onTimeout
  File "timers.js", line 482, col 11, in ontimeout
  File "timers.js", line 317, col 5, in tryOnTimeout
  File "timers.js", line 277, col 5, in Timer.listOnTimeout

数据库连接代码:

const mongoose = require('mongoose');
const log = require('./log');

const options = {
  reconnectTries: 30,
  reconnectInterval: 500,
  poolSize: Number(process.env.DB_POOLSIZE) || 1,
  socketTimeoutMS: 30000,
  keepAlive: true,
  bufferCommands: false,
  bufferMaxEntries: 0,
};

let isConnected;

module.exports.connect = () => new Promise((resolve, reject) => {
  if (isConnected) {
    return resolve();
  }

  return mongoose.connect(process.env.DB_URI, options)
    .then((db) => {
      isConnected = db.connections[0].readyState;
      resolve();
    }).catch((error) => {
      log.error('DB:', error);
      reject(error);
    });
});

我检查过 - isConnected 缓存成功,mongodb 连接缓存在 mongoose 中。一切都必须没问题,但有时我会收到此错误。

有人知道我该如何解决这个问题吗?

最佳答案

只需增加 socketTimeoutMS - 对我来说 2000000 足以在“热”容器的 lambda 调用之间保持连接。 使用下一个配置( Mongoose ):

 { reconnectTries: 30, reconnectInterval: 500, poolSize: 1, socketTimeoutMS: 2000000, keepAlive: true, }

另一个变体(smbd 将此视为最佳实践)- 为每个 lambda 调用创建/关闭连接。如果您知道 lambda 将很少被调用,这不是个坏主意

关于node.js - AWS Lambda(Node.js,8.10 版)和 Mongoose : MongoNetworkError connection to DB timed out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54226024/

相关文章:

node.js - Passport jwt 验证回调未调用

node.js - 使用 pm2 扩展 Nodejs 应用程序

mongodb - 抑制 Codeship 服务的输出

javascript - 无法理解复杂的 $group'ing/aggregation

node.js - 使用 Mongoose 从多个 MongoDB 集合中查找有限制的文档并作为返回排序列表

node.js - 无法让 PUT 在 Nodejs/express 上工作

node.js - 将 Angular Universal 部署到 IIS

node.js - 统计 Mongo 中引用对象的数量

javascript - 当路径有空格时,NodeJS fs.writeFile 在 Linux 上失败

javascript - 如何填充嵌套数组引用? Mongoose