Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Redis Listener

Is it possible to listen to a changed value event from redis in nodejs?

Situation: I have a NodeJS application which shows real time data from another application (native application on the same server, lets call it foo and lets call the node application bar).

Foo saves the machine state in the redis key "state". Bar registers this and displays it. How can you capture this event?

Edit Pierres Solution works fine for getting the keys but how do I retrieve the values? I tried it this way, however a parseError occurs:

var redis = require("redis");
var client_redis = redis.createClient();

client_redis.config('set', 'notify-keyspace-events', 'KEA');
client_redis.subscribe('__keyevent@0__:set');
client_redis.on('message', function(channel, key) {
  client_redis.get(key, function(error, result) {
    if (error) console.log(error);
    else console.log(result);
  });
});

Error

$ { ReplyError> at parseError (/home/pi/Website/node_modules/redis-parser/lib/parser.js:181:12) -bash: syntax error near unexpected token `('

Edit #2

It seems like client_redis.subscribe('...') blocks the client from reading values to the corresponding keys. I added a second client which reads the value.

Working Example:

var redis = require("redis");
// Client for subscription
var subscriptionClient = redis.createClient();
// Client for reading the values from the keys. 
var readClient = redis.createClient();


subscriptionClient.config('set', 'notify-keyspace-events', 'KEA');
// subscribe to the key event so we get notificated if a value changes
subscriptionClient.subscribe('__keyevent@0__:set');

subscriptionClient.on('message', function(channel, key) {
  readClient.get(key, function(err, value) {
     console.log(value);
  });
});
like image 527
FRules Avatar asked Sep 16 '26 20:09

FRules


1 Answers

Yes, it is possible. You need to use Redis Keyspace Notifications.

See especially the Events generated by different commands part. You probably want to be notified when the SET command is used :

var redis = require('redis');
var client_redis = redis.createClient();

// enable notify-keyspace-events for all kind of events (can be refined)
client_redis.config('set','notify-keyspace-events','KEA');

client_redis.subscribe('__keyevent@0__:set');
// you can target a specific key with a second parameter
// example, client_redis.subscribe('__keyevent@0__:set', 'mykey')

client_redis.on('message', function(channel, key) {
  // do what you want when a value is updated
});
like image 134
Pierre Maoui Avatar answered Sep 19 '26 12:09

Pierre Maoui