默认配置是这样的:notify-keyspace-events ""
根据文档中的说明:
K Keyspace events, published with __keyspace@<db>__ prefix.
E Keyevent events, published with __keyevent@<db>__ prefix.
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
$ String commands
l List commands
s Set commands
h Hash commands
z Sorted set commands
x Expired events (events generated every time a key expires)
e Evicted events (events generated when a key is evicted for maxmemory)
A Alias for g$lshzxe, so that the "AKE" string means all the events.我们配置为:notify-keyspace-events Ex,含义为:发布key事件,使用过期事件(当每一个key失效时,都会生成该事件)。 2.准备客户端和连接配置
public class TestThread extends Thread {
private Log log= LogFactory.getLog(TestThread.class);
private JedisPool pool;
public TestThread(JedisPool pool){
log.info("loading test thread");
this.pool= pool;
}
@Override
public void run() {
Jedis jedis= pool.getResource();
jedis.psubscribe(new MySubscribe(), "*");
try {
Thread.sleep(10000L);
} catch (InterruptedException e) {
log.info("延时失败", e);
}
jedis.close();
log.info("Test run finished");
}
}在测试线程中,我们将自定义的MySubscribe加入到了Jedis的模板订阅(即psubscribe,因为模板订阅的channel是支持星号'*'通配的,这样可以收集到多个通配通道的消息,而与之相反的还有一个subscribe,此订阅只能指定严格匹配的通道)中,同样为了测试过程能够将结果显示出来,在绑定了订阅后,对该线程进行了延时10秒。
public class MySubscribe extends JedisPubSub {
private static final Log log= LogFactory.getLog(MySubscribe.class);
// 初始化按表达式的方式订阅时候的处理
public void onPSubscribe(String pattern, int subscribedChannels) {
log.info(pattern + "=" + subscribedChannels);
}
// 取得按表达式的方式订阅的消息后的处理
public void onPMessage(String pattern, String channel, String message) {
log.info(pattern + "=" + channel + "=" + message);
}
...其他未用到的重写方法忽略
}作为Jedis自定义订阅,必须继承redis.clients.jedis.JedisPubSub类,在psubscribe模式下,重点重写onPMessage方法,该方法为接收到模板订阅后处理事件的重要代码。pattern为在绑定订阅时使用的通配模板,channel为通配后符合条件的实际通道名称,message就不用多说了,就是事件消息内容。
3.实战
通过Redis自带的redis-cli命令,我们可以在服务端通过命令行的方式直接操作。我们运行上面的示例代码,然后迅速切换到redis-cli命令中,建立一个生命周期很短暂的数据:
127.0.0.1:6379> set chaijunkun 123 PX 100PX参数指定生命周期单位为毫秒,100即声明周期,即100毫秒。key为chaijunkun的数据,其值为123。
当执行语句后,回显:
OK
之前的代码中,对于事件的发布都是由Redis自己生成的。实际上在命令中主动发布自定义消息也是可以的,在publish命令的帮助中我们看到:
127.0.0.1:6379> help publish
PUBLISH channel message
summary: Post a message to a channel
since: 2.0.0
group: pubsub