简体   繁体   中英

Can not connect to Redis inside MongoClient.connect

I'm having trouble to connect Redis inside MongoClient.connect.

Although both separately works, inside mongo s callback somehow Redis does not connect.

My file structure is like this:

mongoUtil.js:

const chalk       = require( 'chalk' )
const MongoClient = require( 'mongodb' ).MongoClient
const appConfig   = require( '../config/appConfig' )

let _db

module.exports = {

 connectToServer: callback => {
   MongoClient.connect(
     appConfig.MONGO_URL,
     { promiseLibrary: Promise },
     ( err, db ) => {
       _db = db;
       console.log( chalk.blue('Connected to MongoDB') )
       callback( err )
     }
   )
 },

 getDb: function() {
  return _db;
 }
}

redisUtil.js:

const chalk       = require( 'chalk' )
const redis       = require('redis')

let client        = redis.createClient()

module.exports = {

  connectToServer : callback => {
    client.on('connect', () => {
    console.log( chalk.red('Connected to Redis') )
    callback()
   } )
},

  getDb: function() {
    return client;
  }
}

server.js: this does not work

const mongoUtil     = require( './lib/mongoUtil' )
const redisUtil     = require( './lib/redisUtil' )

mongoUtil.connectToServer( err => {

  redisUtil.connectToServer( () => {
    // some server code
  })

})

server.js: this works

const mongoUtil     = require( './lib/mongoUtil' )
const redisUtil     = require( './lib/redisUtil' )

redisUtil.connectToServer( () => {
  // some server code
})    

mongoUtil.connectToServer( err => {

})

I suspect this is a timing issue. By the time you call redisUtil.connectToServer the connection to Redis will already have been established, so the connect event won't fire. Calling redis.createClient() will attempt to connect straight away, it won't wait for you to register the connect event listener.

Off the top of my head, something like this should work:

connectToServer: callback => {
    if (client.connected) {
        console.log(chalk.red('Already connected to Redis'));
        callback();
    }
    else {
        client.on('connect', () => {
            console.log(chalk.red('Connected to Redis'));
            callback();
        }
    }
)

I'm not sure whether this will work if the client is in the process of reconnecting. It's also quite misleading having a function called connectToServer when it isn't responsible for kicking off the connection. You might want to consider tweaking your code so that createClient is called inside connectToServer , more like how you have it with Mongo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM