Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use the retryStrategy #70

Closed
Ajido opened this issue Jun 11, 2015 · 4 comments
Closed

How to use the retryStrategy #70

Ajido opened this issue Jun 11, 2015 · 4 comments

Comments

@Ajido
Copy link

Ajido commented Jun 11, 2015

I don’t want to block the program, even if an error occurs, but I want to keep on reconnect always.
In this case, does the code below look OK?

'use strict';

let Promise = require('bluebird');

let Redis = require('ioredis');
let redis = new Redis({
  sentinels: [
    { host: '127.0.0.1', port: 15379 },
    { host: '127.0.0.1', port: 15380 },
    { host: '127.0.0.1', port: 15381 }
  ],
  name: 'mymaster',
  enableOfflineQueue: false,
  retryStrategy: function(times) {
    if (times < 3) {
      return 200;
    }
  }
});

Redis.Promise.onPossiblyUnhandledRejection(function(err) {
  console.error(err);
});

let func = Promise.coroutine(function* () {
  let key = 'foo:' + Math.random();

  // DO NOT STOP IF ERROR OCCURS, BUT KEEP ON RECONNECT
  try {
    yield redis.setex(key, 10, 'xxxxxxxxx');
    let value = yield redis.get(key);
    console.log(Date.now(), value);
  }
  catch (err) {
    console.error(err);
  }
});

let loop = function() {
  func().then(loop).catch(function(err) {
    console.error(err.stack);
    process.exit(1);
  });
}

redis.on('end', function() {
  // Reconnect manually after finished all retry
  redis.connect();
});

redis.once('ready', function() {
  loop();
});
@luin
Copy link
Collaborator

luin commented Jun 11, 2015

Looks good to me. Does it work?

@Ajido
Copy link
Author

Ajido commented Jun 11, 2015

Yes, it works.
Thanks!

@Ajido Ajido closed this as completed Jun 11, 2015
@luin
Copy link
Collaborator

luin commented Jun 12, 2015

Just a note, the following code also works:

var redis = new Redis(6880);

var func = Redis.Promise.coroutine(function *() {
  try {
    // set timeout
    var bar = yield redis.get('foo').timeout(1000);
  } catch (e) {
    console.log(e);
    // e: [TimeoutError: operation timed out]
  }
  console.log('bar', bar);
});

func();

@Ajido
Copy link
Author

Ajido commented Jun 12, 2015

I didn't know that. Thank you, I will.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants