当断开连接并且connectTimeoutMS结束时,我想做点什么。我在我的猫鼬配置中使用了这个选项:
var options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
所以在30秒后它放弃尝试重新连接。有没有很好的解决方案,所以我可以处理放弃事件?我想在connectTimeoutMS出来之后做一些事情。 它应首先尝试重新连接30秒,然后如果失败 - 发出警告,表示它无法重新连接。
答案 0 :(得分:1)
你的活着太低了。来自官方文档 -
对于长时间运行的应用程序,启用keepAlive通常是谨慎的 有几毫秒。没有它,经过一段时间 您可能会开始看到“连接已关闭”错误,似乎没有 原因。如果是这样,在阅读完之后,您可以决定启用keepAlive
答案 1 :(得分:0)
您必须查看error
回调中的mongoose.connect
对象。
var mongoose = require('mongoose');
var retryAttempts = 0;
var options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 1000 } }
};
function mongoConnect() {
mongoose.connect('mongodb://127.1.2.3/test', options, function (error) {
if (error && error.message.indexOf('timed out') > -1) {
if (retryAttempts++ < 5) {
console.log('Retrying...');
mongoConnect();
}
else {
console.log('Could not connect after %d attempts', retryAttempts-1);
}
}
});
}
mongoConnect();
例如,您可以使用async.doWhilst
函数来避免递归方法。