Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis client to listen to SET and DEL events

Tags:

node.js

redis

I can easily use Redis Pub/Sub functionality to send messages between Redis clients, but I am having trouble finding the syntax to listen to basic Redis events like SET or DEL. I want to create a client that will listen for basic Redis events like the udpating of a key/value pair, but none of the Pub/Sub libraries that I can find give examples of how to listen to basic events like deletes or sets.

For example, I am looking for something along the lines of:

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

client.on('SET', function(result){
//this will be invoked when any key or a specific key is set
}

client.on('DEL', function(result){
//this will be invoked when any key or a specific key is deleted
}

does this high-level code exist yet?

http://redis.io/topics/notifications

like image 654
Alexander Mills Avatar asked Mar 16 '23 08:03

Alexander Mills


1 Answers

Yes, this is possible! Here is an example based off of your code:

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

var EVENT_SET = '__keyevent@0__:set';
var EVENT_DEL = '__keyevent@0__:del';

client.on('message', function(channel, key) {
  switch (channel) {
  case EVENT_SET:
    console.log('Key "' + key + '" set!');
    break;
  case EVENT_DEL:
    console.log('Key "' + key + '" deleted!');
    break;
  }
});

client.subscribe(EVENT_SET, EVENT_DEL);

Before attempting to run the above code, remember to set notify-keyspace-events correctly in your server configuration, for example:

notify-keyspace-events "Eg$"
like image 119
Tim Cooper Avatar answered Mar 25 '23 03:03

Tim Cooper