【发布时间】:2019-06-11 01:38:50
【问题描述】:
环境:
- AWS Lambda(Node.js,v. 8.10),waitForEmptyEventLoop === false
- MongoDB(阿特拉斯)
- 猫鼬
问题:有时(随机)我得到下一个错误:
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
db连接代码:
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 中。一切都应该没问题,但有时我会收到此错误。
有人知道我该如何解决这个问题吗?
【问题讨论】:
-
这里有同样的问题,在生产/开发环境中,我在大约 1% 的执行中看到了这个错误。您找到任何解决方案/解决方法了吗?
-
@RodrigoReis 我使用下一个配置(猫鼬):
{ reconnectTries: 30, reconnectInterval: 500, poolSize: 1, socketTimeoutMS: 2000000, keepAlive: true, } -
只需增加 socketTimeoutMS - 对我来说 2000000 足以保持 lambdas 调用“温暖”容器之间的连接
-
另一种变体(smbd 将此视为最佳实践) - 为每个 lambda 调用创建/关闭连接。如果您知道 lambda 将很少被调用,那就不错了
-
谢谢@max-vinogradov。我会尝试提到的配置。如果它真的对你有用,你应该作为答案发布:)
标签: node.js mongodb mongoose aws-lambda serverless