1
\$\begingroup\$

I'm learning Node and Redis and created a semaphore for master/slaves.

var redis = require("redis"),
    _ = require('underscore'),
    async = require('async'),
    client = redis.createClient();

var isMaster = false,
    SEMAPHORE_ADDRESS = 'semaphore';
var lifeCycle = function(next) {
  if(isMaster) {
    client.set([SEMAPHORE_ADDRESS, true, 'EX', 5], function(err, val) {
      console.log('master lifecycle');
      if(err !== null) { throw err; }
      else if(val === 'OK') {
        console.log('everything ok; I will send slaves some tasks');
      } else {
        assert.fail();
      }
      next();
    });
  } else {
    console.log('slave lifecycle');
    client.set([SEMAPHORE_ADDRESS, true, 'NX', 'EX', 5], function(err, val) {
      if(err !== null) { throw err; }
      if(val === null) {
        console.log('slaves takes some tasks');
      } else if(val === 'OK') {
        console.log('I`m master');
        isMaster = true;
      }
      next();
    });
  }
};
async.forever(
  function(next) {
    setTimeout(
      lifeCycle.bind(null, next),
      1000
    );
  }
);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.