1. 事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发,故需要订
阅 __keyevent@0__:expired 通道
0表示db0 根据自己的dbindex选择合适的数字
2. 修改 redis.conf 文件
修改 notify-keyspace-events Ex
# K 键空间通知,以__keyspace@__为前缀 # E 键事件通知,以__keysevent@__为前缀 # g del , expipre , rename 等类型无关的通用命令的通知, ... # $ String命令 # l List命令 # s Set命令 # h Hash命令 # z 有序集合命令 # x 过期事件(每次key过期时生成) # e 驱逐事件(当key在内存满了被清除时生成) # A g$lshzxe的别名,因此”AKE”意味着所有的事件
3. 重启redis , 即可测试失效事件的触发, 监听获取的值为 key
1. 首先需要一个消息监听器类
package com.sogou.baike.testimport.testSubscribe; import redis.clients.jedis.JedisPubSub; /** * Created by denglinjie on 2016/6/29. */ public class RedisMsgPubSubListener extends JedisPubSub { @Override public void unsubscribe() { super.unsubscribe(); } @Override public void unsubscribe(String... channels) { super.unsubscribe(channels); } @Override public void subscribe(String... channels) { super.subscribe(channels); } @Override public void psubscribe(String... patterns) { super.psubscribe(patterns); } @Override public void punsubscribe() { super.punsubscribe(); } @Override public void punsubscribe(String... patterns) { super.punsubscribe(patterns); } @Override public void onMessage(String channel, String message) { System.out.println("channel:" + channel + "receives message :" + message); this.unsubscribe(); } @Override public void onPMessage(String pattern, String channel, String message) { } @Override public void onSubscribe(String channel, int subscribedChannels) { System.out.println("channel:" + channel + "is been subscribed:" + subscribedChannels); } @Override public void onPUnsubscribe(String pattern, int subscribedChannels) { } @Override public void onPSubscribe(String pattern, int subscribedChannels) { } @Override public void onUnsubscribe(String channel, int subscribedChannels) { System.out.println("channel:" + channel + "is been unsubscribed:" + subscribedChannels); } }
该类需要继承JedisPubSub ,并实现其抽象方法,通过方法的名称很清楚的看出来,这个监听器是用来订阅一个频道,在订阅该频道,取消订阅,收到消息等状态会对应调用相关的方法
2. 订阅测试类
public class TestSubscribe { @Test public void testSubscribe() throws Exception{ Jedis jedis = new Jedis("localhost"); RedisMsgPubSubListener listener = new RedisMsgPubSubListener(); jedis.subscribe(listener, "__keyevent@0__:expired"); //other code } }
该类实现对频道redisChatTest的订阅监听,频道的订阅,取消订阅,收到消息都会调用listener对象的对应方法
注意:subscribe是一个阻塞的方法,在取消订阅该频道前,会一直阻塞在这,只有当取消了订阅才会执行下面的other code,参考上面代码,我在onMessage里面收到消息后,调用了this.unsubscribe(); 来取消订阅,这样才会执行后面的other code
3. 发布消息测试类
Public class TestPublish { @Test public void testPublish() throws Exception{ Jedis jedis = new Jedis("localhost"); jedis.publish("redisChatTest", "我是天才"); Thread.sleep(5000); jedis.publish("redisChatTest", "我牛逼"); Thread.sleep(5000); jedis.publish("redisChatTest", "哈哈"); } }
这个类向频道redisChatTest发布消息,第二步因为订阅了该频道,所以会收到该消息。