Reliably reconnect to MongoDB

后端 未结 7 874
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 19:24

UPDATE: I am using the 2.1 version on the driver, against 3.2

I have a node application that uses MongoDB. The problem I have is that if the MongoDB

7条回答
  •  轮回少年
    2020-12-13 19:52

    package.json: "mongodb": "3.1.3"

    Reconnect existing connections

    To fine-tune the reconnect configuration for pre-established connections, you can modify the reconnectTries/reconnectInterval options (default values and further documentation here).

    Reconnect initial connection

    For the initial connection, the mongo client does not reconnect if it encounters an error (see below). I believe it should, but in the meantime, I've created the following workaround using the promise-retry library (which uses an exponential backoff strategy).

    const promiseRetry = require('promise-retry')
    const MongoClient = require('mongodb').MongoClient
    
    const options = {
      useNewUrlParser: true,
      reconnectTries: 60,
      reconnectInterval: 1000,
      poolSize: 10,
      bufferMaxEntries: 0
    }
    
    const promiseRetryOptions = {
      retries: options.reconnectTries,
      factor: 1.5,
      minTimeout: options.reconnectInterval,
      maxTimeout: 5000
    }
    
    const connect = (url) => {
      return promiseRetry((retry, number) => {
        console.log(`MongoClient connecting to ${url} - retry number: ${number}`)
        return MongoClient.connect(url, options).catch(retry)
      }, promiseRetryOptions)
    }
    
    module.exports = { connect }
    

    Mongo Initial Connect Error: failed to connect to server [db:27017] on first connect

提交回复
热议问题