Anda lupa berlangganan klien pelanggan ke saluran tertentu. Selanjutnya, jika Anda ingin menonton semua acara, Anda perlu menggunakan langganan berbasis pola.
Anda mungkin ingin melakukan sesuatu seperti ini (belum diuji):
subscriber.on("pmessage", function (pattern, channel, message) {
console.log("("+ pattern +")" + " client received message on " + channel + ": " + message);
switch (channel) {
// blah blah blah
// ...
}
});
subscriber.psubscribe(''__key*__:*')
Lihat informasi selengkapnya dalam dokumentasi Redis, dan dalam contoh node_redis.
Pembaruan:
Berikut adalah contoh untuk menggambarkan perbedaan antara berlangganan saluran dan berlangganan pola. Penanganan kesalahan yang tepat dihilangkan demi singkatnya.
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();
});
});
Hasil dari script ini adalah:
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
Anda dapat melihat bahwa pelanggan pertama hanya menerima acara untuk kunci saya, sedangkan pelanggan kedua menerima acara untuk semua kunci.