如何处理node-mongodb-native中的连接问题
如何停止缓冲查询,而当应用程序和数据库之间不存在连接时抛出错误?
我正在使用node-mongodb-native驱动程序。
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://someremotedb:27017/test'; var db = null, xcollection = null;
正如在这个答案中build议,我正在打开一个连接,并保留它以备后用。
function connect() { MongoClient.connect(url, function(err, _db) { db = _db; xcollection = db.collection('xcollection'); db.on('close', function() { console.log("connection close mongoDB"); connection_retry(); }); db.on('error', function(err) { console.log("connection err mongoDB ",err); connection_retry(); db.close(); }); }); }
我就这样使用它
module.exports.xcollection_find = function (_x, _cb) { try { xcollection.findOne({x: _x}, { _id: 0 }, function(err, doc) { if(err) return _cb(err, null); if(doc===null) return _cb(null, {success: false, data: null}); return _cb(null, {success: true, data: doc}); }); } catch(e) { return _cb(e, null); } }
我打电话连接,然后一切正常工作正常。
除了当我中断互联网连接到数据库。 (即断开互联网与我的电脑上运行的应用程序),我没有看到任何错误。 所有的请求都使这个消息超时。
[MongoError: server c99.kahana.mongohq.com:27017 received an error {"name":"MongoError","message":"read ETIMEDOUT"}]
但是在超时发生之前大约需要5到10分钟。
如果closures或错误事件被抛出,我的重新连接function会触发。
function connection_retry () { console.log("connection retry mongoDB"); setTimeout(function() { connect(); }, 500); }
但它从来没有。
如果networking连接在超时发生之前恢复(即-5-10分钟),则执行查询并接收结果。
如何检测xcollection_find方法中的连接已closures?
为什么closures或错误的callback没有执行?
更新:
var options = { db: { bufferMaxEntries: 2 }, server: { socketOptions: { keepAlive: true, connectTimeoutMS: 2000 }, auto_reconnect: true } } MongoClient.connect(url, options, function(err, _db) {
将bufferMaxEntries设置为2仍然不能解决问题,请求被caching并在重新连接时发生。
当您的应用启动并重新使用db对象时,您将打开一次MongoClient.connect。 这不是一个单独连接池每个.connect创build一个新的连接池。 因此,一旦在所有请求中重用,就打开它。
https://groups.google.com/forum/#!msg/node-mongodb-native/mSGnnuG8C1o/Hiaqvdu1bWoJ
Node.js是单线程的,你不应该打开以及在相同的请求closures连接。