Du glemte at abonnere på abonnentklienten på en bestemt kanal. Desuden, hvis du vil se til alle begivenheder, skal du bruge et mønsterbaseret abonnement.
Du vil måske gøre noget som dette (utestet):
subscriber.on("pmessage", function (pattern, channel, message) {
console.log("("+ pattern +")" + " client received message on " + channel + ": " + message);
switch (channel) {
// blah blah blah
// ...
}
});
subscriber.psubscribe(''__key*__:*')
Se mere information i Redis-dokumentationen og i eksempler på node_redis.
Opdatering:
Her er et eksempel for at illustrere forskellen mellem kanalabonnement og mønsterabonnement. Korrekt fejlhåndtering er udeladt for kortheds skyld.
var redis = require("redis");
var client = redis.createClient('6379','127.0.0.1');
var subscriber1 = redis.createClient('6379','127.0.0.1');
var subscriber2 = redis.createClient('6379','127.0.0.1');
// First subscriber listens only to events occurring for key mykey
function S1(next) {
subscriber1.on('message', function(channel, msg) {
console.log( "S1: received on "+channel+" event "+msg )
});
subscriber1.subscribe( "[email protected]__:mykey", function (err) {
next();
});
}
// Second subscriber listens to events occuring for ALL keys
function S2(next) {
subscriber2.on('pmessage', function(pattern,channel, msg) {
console.log( "S2: received on "+channel+" event "+msg )
});
subscriber2.psubscribe( "[email protected]__:*", function (err) {
next();
});
}
// Do something with keys mykey and anotherkey
function do_something() {
client.set("mykey","example", function( err ) {
client.set("mykey", "another example", function( err ) {
client.del("mykey", function( err ) {
client.set("anotherkey","example", function( err ) {
client.del("anotherkey");
});
});
});
});
}
// Here we go
S1( function () {
S2( function () {
do_something();
});
});
Resultatet af dette script er:
S1: received on [email protected]__:mykey event set
S2: received on [email protected]__:mykey event set
S2: received on [email protected]__:mykey event set
S1: received on [email protected]__:mykey event set
S1: received on [email protected]__:mykey event del
S2: received on [email protected]__:mykey event del
S2: received on [email protected]__:anotherkey event set
S2: received on [email protected]__:anotherkey event del
Du kan se, at den første abonnent kun modtog begivenheder for mykey, mens den anden abonnent modtager begivenheder for alle nøgler.