发布/订阅

时间:2015-02-05 18:53:24

标签: javascript node.js publish-subscribe eventemitter

我尝试在Node中实现发布/订阅模式但没有Redis。功能应该是相同的;您可以发布到频道,订阅频道并在订阅时收听数据;这是Redis的功能:

pub.publish('channel1', myData1, function (err, data) {     
});


sub.subscribe('channel1', function (err, data) {
});


sub.on("message", function (channel, data) {
    //Now you are easily listening to data
});

我尝试了以下内容,这可能不是一个好方法(我只是展示我的尝试!);我有自己的频道对象,我在这里保存了当我们向特定频道发布新数据时需要触发的频道和功能;所以当你看到我正在为频道订阅功能时;但是,我不知道是否有任何方式可以像redis提供的那样收听数据sub.on("message",function(){...!所以,如果我可以像Redis那样做,请使用eventEmitter或者......来帮助我。

var events = require('events');
var emitter = new events.EventEmitter;
var channels = {};
//channels ={"channelA": ["func1", "func2"], "channelB": []}

//publish data to a channel and emits all of the functions which are registered for listening to the channel
function publish(channel, data, callback) {
    if (channels[channel] && channels[channel].length > 0) {
        for (var i = 0; i < channels[channel].length; i++) {
            emitter.emit(channels[channel][i], data);
        }
    }
    callback();

}

//subscribe a function to a channel
function subscribe(channel, FuncName, next) {
    if (!channels[channel]) {
        channels[channel] = [];
    }
    channels[channel].push(FuncName);
    next();
}

//Subscribe a callback function from a channel
function unsubscribe(channel, FuncName) {
    if (channels[channel]) {
        var indx = channels[channel].indexOf(FuncName);
        if (indx != -1) {
            channels[channel].splice(indx, 1);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以为每个频道使用EventEmitter。此外,您可能希望保存对回调的引用,而不是函数名称字符串。

var events = require('events');
var channels = {};

//publish data to a channel and emits all of the functions which are registered for listening to the channel
function publish(channel, data, callback) {
  if (channels[channel]) {
    channels[channel].emit('message', channel, data);
  }
  callback();
}

//subscribe a function to a channel
function subscribe(channel, fn, next) {
  if (!channels[channel]) {
    channels[channel] = new events.EventEmitter();
  }
  channels[channel].addListener('message', fn);
  next();
}

//unsubscribe a callback function from a channel
function unsubscribe(channel, fn) {
  if (channels[channel]) {
    channels[channel].removeListener('message', fn);
  }
}