sync config changes over redis pubsub

This commit is contained in:
barisusakli
2014-12-21 20:25:54 -05:00
parent 2f8e6a1f2b
commit 936ea5f686
3 changed files with 55 additions and 21 deletions

45
src/pubsub.js Normal file
View File

@@ -0,0 +1,45 @@
'use strict';
var nconf = require('nconf'),
util = require('util'),
winston = require('winston'),
EventEmitter = require('events').EventEmitter;
var PubSub = function() {
var self = this;
if (nconf.get('redis')) {
var redis = require('./database/redis');
var subClient = redis.connect();
this.pubClient = redis.connect();
subClient.subscribe('pubsub_channel');
subClient.on('message', function(channel, message) {
if (channel !== 'pubsub_channel') {
return;
}
try {
var msg = JSON.parse(message);
self.emit(msg.event, msg.data);
} catch(err) {
winston.error(err.stack);
}
});
}
};
util.inherits(PubSub, EventEmitter);
PubSub.prototype.publish = function(event, data) {
if (this.pubClient) {
this.pubClient.publish('pubsub_channel', JSON.stringify({event: event, data: data}));
} else {
this.emit(event, data);
}
};
var pubsub = new PubSub();
module.exports = pubsub;