I'm trying to get Redis pub/sub working in a little Node app. Currently I'm using node-redis and I don't understand the API for pub/sub. It seems like I can subscribe to a channel by name and then I receive all messages for all channels in a generic 'message' event, like so:
var express = require('express')
, app = express()
, server = app.listen(4000)
, sio = require('socket.io')
, io = sio.listen(server)
, db = require('redis').createClient();
io.sockets.on('connection', function (socket) {
db.subscribe("foo");
db.subscribe("bar");
db.on("message", function(channel, message) {
socket.emit('message', message);
});
});
This forces me to either create a new client for each subscription or to use something like:
db.on("message", function(channel, message) {
socket.emit(channel, message);
});
and then listen to the right socket.io channel client side. Neither is ideal for me.
What I would like is to register a callback at the time of subscribing so, I receive messages for that channel only, like in this pseudo code snippet:
db.subscribe("foo", function(message) {
socket.emit("foo_message", message);
});
db.subscribe("bar", function(message) {
socket.emit("bar_message", message);
});
Does anybody know a clean solution for my problem or maybe another redis API that supports my wishes?