U bent vergeten de abonneeclient op een specifiek kanaal te abonneren. Als je alle evenementen wilt bekijken, moet je bovendien een op patronen gebaseerd abonnement gebruiken.
Misschien wil je zoiets als dit doen (niet getest):
subscriber.on("pmessage", function (pattern, channel, message) {
console.log("("+ pattern +")" + " client received message on " + channel + ": " + message);
switch (channel) {
// blah blah blah
// ...
}
});
subscriber.psubscribe(''__key*__:*')
Zie meer informatie in de Redis-documentatie en in node_redis-voorbeelden.
Bijwerken:
Hier is een voorbeeld om het verschil tussen kanaalabonnement en patroonabonnement te illustreren. Correcte foutafhandeling is kortheidshalve weggelaten.
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();
});
});
Het resultaat van dit script is:
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
U kunt zien dat de eerste abonnee alleen gebeurtenissen voor mykey heeft ontvangen, terwijl de tweede abonnee gebeurtenissen voor alle sleutels ontvangt.