33

Mongoose 経由で MongoDB 自動再接続機能をセットアップしようとしています。オプションを渡そうとしたすべての方法で効果がなかったか、少なくともreconnectedイベントが発行されていません。

私が試したこと:

mongoose.createConnection("mongodb://localhost:27017/test", { auto_reconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { autoReconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { auto_reconnect: true } });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { autoReconnect: true } });

これらのいずれかが正しい場合、reconnectedイベントがトリガーされ、メッセージがコンソールに記録されるはずですが、これは決して起こりません。

再接続の前に遅延がある場合、それを構成する方法を知っている人はいますか?

前もって感謝します

これを調べている人は、マングースリポジトリでこれこの問題を見てください。

4

10 に答える 10

62

私はあなたと同じ質問をしました.Robertklepの解決策も私にはうまくいきませんでした. MongoDB サービスが停止すると、エラー イベントがトリガーされますが、connection.readyState は 1 (接続済み) のままです。それが自動再接続しなかった理由かもしれません。

これは私が今持っているものです:

  var db = mongoose.connection;

  db.on('connecting', function() {
    console.log('connecting to MongoDB...');
  });

  db.on('error', function(error) {
    console.error('Error in MongoDb connection: ' + error);
    mongoose.disconnect();
  });
  db.on('connected', function() {
    console.log('MongoDB connected!');
  });
  db.once('open', function() {
    console.log('MongoDB connection opened!');
  });
  db.on('reconnected', function () {
    console.log('MongoDB reconnected!');
  });
  db.on('disconnected', function() {
    console.log('MongoDB disconnected!');
    mongoose.connect(dbURI, {server:{auto_reconnect:true}});
  });
  mongoose.connect(dbURI, {server:{auto_reconnect:true}});
于 2013-06-13T17:33:45.180 に答える
12

後世のために、これらの回答のほとんどは古いため、この問題は nodejs mongodb ドライバーに組み込まれているため、これ以上対処する必要はありません。kdmonを引用するには:

...再接続がマングースに組み込まれ、デフォルトで有効になりました。しかし、Mongoose はデフォルトで 30 秒間だけ再接続を試み、その後あきらめることを知っておくと便利です。server.reconnectTries オプションを設定して、mongoose が再接続を試行する回数を増やします。たとえば、次のように mongoose に再接続の試行を停止しないように指示できます。

mongoose.connect(uri, { server: { reconnectTries: Number.MAX_VALUE } });

詳細については、接続ドキュメントサーバー オプションのデフォルトを参照してください。

于 2016-09-25T08:11:26.650 に答える
4

これは、接続試行の間に最低5秒を設定するCliveの回答の改善です。

var db = mongoose.connection;
var lastReconnectAttempt; //saves the timestamp of the last reconnect attempt
db.on('error', function(error) {
    console.error('Error in MongoDb connection: ' + error);
    mongoose.disconnect();
});
db.on('disconnected', function() {
    console.log('MongoDB disconnected!');
    var now = new Date().getTime();
    // check if the last reconnection attempt was too early
    if (lastReconnectAttempt && now-lastReconnectAttempt<5000) {
        // if it does, delay the next attempt
        var delay = 5000-(now-lastReconnectAttempt);
        console.log('reconnecting to MongoDB in ' + delay + "mills");
        setTimeout(function() {
            console.log('reconnecting to MongoDB');
            lastReconnectAttempt=new Date().getTime();
            mongoose.connect(dbURI, {server:{auto_reconnect:true}});
        },delay);
    }
    else {
        console.log('reconnecting to MongoDB');
        lastReconnectAttempt=now;
        mongoose.connect(dbURI, {server:{auto_reconnect:true}});
    }

});
于 2015-10-15T04:02:01.617 に答える
2

@zangwの回答に基づいて、アプリのこのデータベース初期化機能を終了しました

const mongoose = require('mongoose')
const RETRY_TIMEOUT = 3000

module.exports = function initDB () {
  mongoose.Promise = global.Promise
  const options = {
    autoReconnect: true,
    useMongoClient: true,
    keepAlive: 30000,
    reconnectInterval: RETRY_TIMEOUT,
    reconnectTries: 10000
  }

  let isConnectedBefore = false

  const connect = function () {
    return mongoose.connect(process.env.MONGODB_URL, options)
      .catch(err => console.error('Mongoose connect(...) failed with err: ', err))
  }

  connect()

  mongoose.connection.on('error', function () {
    console.error('Could not connect to MongoDB')
  })

  mongoose.connection.on('disconnected', function () {
    console.error('Lost MongoDB connection...')
    if (!isConnectedBefore) {
      setTimeout(() => connect(), RETRY_TIMEOUT)
    }
  })
  mongoose.connection.on('connected', function () {
    isConnectedBefore = true
    console.info('Connection established to MongoDB')
  })

  mongoose.connection.on('reconnected', function () {
    console.info('Reconnected to MongoDB')
  })

  // Close the Mongoose connection, when receiving SIGINT
  process.on('SIGINT', function () {
    mongoose.connection.close(function () {
      console.warn('Force to close the MongoDB connection after SIGINT')
      process.exit(0)
    })
  })
}

いくつかの違いがあります: 接続を閉じる問題を防ぐためにいくつかのオプションを追加しました - 30回の自動再試行後に再接続しません.MongoError: Topology was destroyed for any operation and no reconnect; また、未処理の約束の拒否を防ぐために、接続後に .catch を追加しました):

于 2017-08-23T11:07:41.147 に答える
1

再試行中にリクエストをブロックせずに複数回再試行するには、bufferMaxEntries: 0次のように設定する必要がありました。

const dbUri = 'mongodb://localhost/some_db';
const dbOptions = {
    useMongoClient: true,
    autoReconnect: true,
    reconnectTries: Number.MAX_VALUE,
    bufferMaxEntries: 0
};

mongoose.connect(dbUri, dbOptions).catch(err => process.exit(1));
于 2017-11-17T11:39:11.703 に答える
1

ドキュメントを読んだ後、オプションが間違っていると確信しています。接続オプション文字列は次のようになります。

mongoose.connect("mongodb://localhost:27017/db", {
    socketOptions: {
      // This option is on by default, but why not set it explicitly
      autoReconnect: true
    },
    // This options is 1 second by default, its possible the ha
    // takes longer than 30 seconds to recover.
    reconnectInterval: 5000,
    // This options is 30 by default, why not make it 60
    reconnectTries: 60
  })

このページをチェックしてください: http://mongoosejs.com/docs/api.html

于 2017-01-29T17:23:57.417 に答える