Du glömde att prenumerera på en specifik kanal för prenumerantklienten. Dessutom, om du vill titta på alla evenemang måste du använda mönsterbaserad prenumeration.
Du kanske vill göra något så här (otestat):
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 mer information i Redis-dokumentationen och i node_redis-exempel.
Uppdatering:
Här är ett exempel för att illustrera skillnaden mellan kanalprenumeration och mönsterprenumeration. Korrekt felhantering utelämnas för korthetens skull.
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 av detta skript är:
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 att första prenumerant endast fick händelser för mykey, medan andra prenumerant får händelser för alla nycklar.