Redis客户端侦听SET和DEL事件

时间:2015-04-22 00:05:12

标签: node.js redis

我可以轻松使用Redis Pub / Sub功能在Redis客户端之间发送消息,但是我无法找到语法来侦听基本的Redis事件,如SET或DEL。我想创建一个客户端来监听基本的Redis事件,比如关键/值对的udpating,但是我找不到的Pub / Sub库都没有提供如何监听删除或设置等基本事件的示例。 / p>

例如,我正在寻找以下内容:

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
}

这个高级代码是否存在?

http://redis.io/topics/notifications

1 个答案:

答案 0 :(得分:5)

是的,这是可能的!以下是基于代码的示例:

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);

在尝试运行上述代码之前,请记住在配置中正确设置notify-keyspace-eventsEg$就足够了。)