Node.js 使用 mongodb-native 连接 Mongodb 频繁断开连接,求解决方法?
PHP中文网
PHP中文网 2017-04-17 13:54:27
[Node.js讨论组]

Node.js 6.2.0 版本,mongodb-native 2.1.20 版本。程序不会崩溃,卡在数据库查询位置。

自己实现数据库连接部分代码如下:

// 程序启动时调用数据库连接
mongoConnect.connect(config.mongodb.master.url, function (err, db) {
  if (err) {
    console.log(err);
    process.exit(1);
  } else {
    app.listen(config.server.port, function () {
      console.log('apps server start at: ' + config.server.port);
    });

    module.exports = app;
  }
});
// 连接数据库
'use strict';

var MongoClient = require('mongodb').MongoClient;

var mongo = {
  '_db': null,
  '_mongodbUrl': null,
  '_connectOptions': {
    'server':{
      'auto_reconnect': true,
      'poolSize': 10,
      'socketOptions':{
        'keepAlive': 1
      }
    },
    'db': {
      'numberOfRetries': 10,
      'retryMiliSeconds': 1000
    }
  },

  connect(mongodbUrl, callback) {
    var that = this;
    if (!mongodbUrl) {
      reject(new Error('missing parameter "mongodbUrl"'));
    } else {
      that._mongodbUrl = mongodbUrl;
      MongoClient.connect(that._mongodbUrl, that._connectOptions, function (err, db) {
        if (err) {
          console.log(err);
          that._db = null;
          callback(err);
        } else {
          db.on('close', function () {
            console.log('mongodb server closed');
            that._db = null;
          });
          db.on('timeout', function () {
            console.log('mongodb server timeout');
            that._db = null;
          });
          db.on('error', function () {
            console.log('mongodb server closed');
            that._db = null;
          });

          that._db = db;
          callback(null, that._db);
        }
      });
    }
  },
  
  getInstance(callback) {
    var that = this;
    if (!that._db) {
      console.log('reconnect to mongodb');
      that.connect(that._mongodbUrl, (err, db) => {
        if (err) {
          callback(err);
        } else {
          callback(null, db);
        }
      });
    } else {
      console.log('use exists mongodb instance');
      callback(null, that._db);
    }
  }
};

module.exports = mongo;
// 使用数据库
  mongo.getInstance(function (err, db) {
    var collection = db.collection('users');
    collection.find({}).limit(10).toArray(function (err, users) {
      if (err) {
        res.send(err);
      } else {
        res.send(users);
      }
    });
  });

出错后,尝试了 Does mongoDB have reconnect issues or am i doing it wrong? 下的所有解决方法,依旧无解。

现在使用 generic-pool 做数据库连接部分,断线频率降低,但是还是会出现断线状况,这时只有重启服务才能解决。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号