gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:45:16 27 4
gpt4 key购买 nike

环境:

  • 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com