redis自2.8.0之后版本提供Keyspace Notifications功能,允许客户订阅Pub / Sub频道,以便以某种方式接收影响Redis数据集的事件。
可能收到的事件的例子如下:
所有影响给定键的命令。
所有接收LPUSH操作的密钥。
所有密钥在数据库中过期0。
因为 Redis 目前的订阅与发布功能采取的是发送即忘(fire and forget)策略, 所以如果你的程序需要可靠事件通知(reliable notification of events), 那么目前的键空间通知可能并不适合你:当订阅事件的客户端断线时, 它会丢失所有在断线期间分发给它的事件。并不能确保消息送达。未来有计划允许更可靠的事件传递,但可能这将在更一般的层面上解决,或者为Pub / Sub本身带来可靠性,或者允许Lua脚本拦截Pub / Sub消息来执行诸如推送将事件列入清单。
事件类型
对于每个修改数据库的操作,键空间通知都会发送两种不同类型的事件消息:keyspace 和 keyevent。以 keyspace 为前缀的频道被称为键空间通知(key-space notification), 而以 keyevent 为前缀的频道则被称为键事件通知(key-event notification)。
事件是用 __keyspace@DB__:KeyPattern 或者 __keyevent@DB__:OpsType 的格式来发布消息的。
DB表示在第几个库;KeyPattern则是表示需要监控的键模式(可以用通配符,如:__key*__:*);OpsType则表示操作类型。因此,如果想要订阅特殊的Key上的事件,应该是订阅keyspace。
比如说,对 0 号数据库的键 mykey 执行 DEL 命令时, 系统将分发两条消息, 相当于执行以下两个 PUBLISH 命令:
PUBLISH __keyspace@0__:sampleKey del
PUBLISH __keyevent@0__:del sampleKey
订阅第一个频道 __keyspace@0__:mykey 可以接收 0 号数据库中所有修改键 mykey 的事件, 而订阅第二个频道 __keyevent@0__:del 则可以接收 0 号数据库中所有执行 del 命令的键。
开启配置
键空间通知通常是不启用的,因为这个过程会产生额外消耗。所以在使用该特性之前,请确认一定是要用这个特性的,然后修改配置文件,或使用config配置。相关配置项如下:
字符 | 发送通知 |
---|---|
K | 键空间通知,所有通知以 keyspace@ 为前缀,针对Key |
E | 键事件通知,所有通知以 keyevent@ 为前缀,针对event |
g | DEL 、 EXPIRE 、 RENAME 等类型无关的通用命令的通知 |
$ | 字符串命令的通知 |
l | 列表命令的通知 |
s | 集合命令的通知 |
h | 哈希命令的通知 |
z | 有序集合命令的通知 |
x | 过期事件:每当有过期键被删除时发送 |
e | 驱逐(evict)事件:每当有键因为 maxmemory 政策而被删除时发送 |
A | 参数 g$lshzxe 的别名,相当于是All |
输入的参数中至少要有一个 K 或者 E , 否则的话, 不管其余的参数是什么, 都不会有任何通知被分发。上表中斜体的部分为通用的操作或者事件,而黑体则表示特定数据类型的操作。配置文件中修改 notify-keyspace-events “Kx”,注意:这个双引号是一定要的,否则配置不成功,启动也不报错。例如,“Kx”表示想监控某个Key的失效事件。
也可以通过config配置:CONFIG set notify-keyspace-events Ex (但非持久化)
Redis 使用以下两种方式删除过期的键:
1.当一个键被访问时,程序会对这个键进行检查,如果键已经过期,那么该键将被删除。
2.底层系统会在后台查找并删除那些过期的键,从而处理那些已经过期、但是不会被访问到的键。
当过期键被以上两个程序的任意一个发现、 并且将键从数据库中删除时, Redis 会产生一个 expired 通知。
Redis 并不保证生存时间(TTL)变为 0 的键会立即被删除: 如果程序没有访问这个过期键, 或者带有生存时间的键非常多的话, 那么在键的生存时间变为 0 , 直到键真正被删除这中间, 可能会有一段比较显著的时间间隔。
因此, Redis 产生 expired 通知的时间为过期键被删除的时候, 而不是键的生存时间变为 0 的时候。
由于通知收到的是redis key,value已经过期,无法收到,所以需要在key上标记业务数据。
实现思路:
1,利用MessageListenerAdapter,spring本身已经提供了的实现方式。
首先自定义一个MessageDelegate 接口并实现
1 public interface MyMessageDelegate {
2 void handleMessage(String message);
3 void handleMessage(Map message); void handleMessage(byte[] message);
4 void handleMessage(Serializable message);
5 // pass the channel/pattern as well
6 void handleMessage(Serializable message, String channel);
7 }
8
9 public class MyRedisKeyExpiredMessageDelegate implements MessageDelegate {
10 // implementation elided for clarity...
11 }
xml相关配置
<bean id="messageListener"
class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<bean class="com.ky.sdn.mq.service.impl.DefaultMqMessageDelegate" />
</constructor-arg>
</bean>
<bean id="redisContainer"
class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="messageListeners">
<map>
<entry key-ref="messageListener">
<list>
<bean class="org.springframework.data.redis.listener.ChannelTopic">
<constructor-arg value="__keyevent@0__:expired" />
</bean>
<bean class="org.springframework.data.redis.listener.PatternTopic">
<constructor-arg value="'__key*__:*" />
</bean>
</list>
</entry>
</map>
</property>
</bean>
具体可参考官方文档:http://docs.spring.io/spring-data/redis/docs/1.7.8.RELEASE/reference/html/#redis:pubsub:subscribe
2.即自定义一个KeyExpiredListener类继承自JedisPubSub。
import redis.clients.jedis.JedisPubSub;
public class KeyExpiredListener extends JedisPubSub {
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.println("onPSubscribe "
+ pattern + " " + subscribedChannels);
}
@Override
public void onPMessage(String pattern, String channel, String message) {
System.out.println("onPMessage pattern "
+ pattern + " " + channel + " " + message);
}
}
订阅者
public class Subscriber {
public static void main(String[] args) {
JedisPool pool = new JedisPool(new JedisPoolConfig(), "192.168.100.62", 6379, 3000, "kaiyuan");
Jedis jedis = pool.getResource();
jedis.psubscribe(new KeyExpiredListener(), "__key*__:*");
pool.close();
}
}
测试
public class TestJedis {
public static void main(String[] args) {
JedisPool pool = new JedisPool(new JedisPoolConfig(), "192.168.100.62", 6379, 3000, "kaiyuan");
Jedis jedis = pool.getResource();
jedis.set("sla_zw_line_lock_sssssss", "写啥都行");
jedis.expire("sla_zw_line_lock_sssssss", 3);
pool.close();
}
}
结果
onPSubscribe __key*__:* 1
onPMessage pattern __key*__:* __keyevent@0__:expired sla_zw_line_lock_sssssss
onPMessage pattern __key*__:* __keyevent@0__:expired sla_zw_line_lock_sssssss
其中第一行的打印是启动订阅者的时候才打印1次
3,发布和订阅的方式
特性介绍
Pub/Sub功能(means Publish, Subscribe)即发布及订阅功能。基于事件的系统中,Pub/Sub是目前广泛使用的通信模型,它采用事件作为基本的通信机制,提供大规模系统所要求的松散耦合的交互模式:订阅者(如客户端)以事件订阅的方式表达出它有兴趣接收的一个事件或一类事件;发布者(如服务器)可将订阅者感兴趣的事件随时通知相关订阅者。
监听者
public class SubscriberListener extends JedisPubSub {
public SubscriberListener(){}
@Override
public void onMessage(String channel, String message) { //收到消息会调用
System.out.println(String.format("receive redis published message, channel %s, message %s", channel, message));
}
@Override
public void onSubscribe(String channel, int subscribedChannels) { //订阅了频道会调用
System.out.println(String.format("subscribe redis channel success, channel %s, subscribedChannels %d",
channel, subscribedChannels));
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) { //取消订阅 会调用
System.out.println(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d",
channel, subscribedChannels));
}
}
发布者
public class Publisher extends Thread{
private final JedisPool jedisPool;
public Publisher(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Jedis jedis = jedisPool.getResource(); //连接池中取出一个连接
while (true) {
String line = null;
try {
line = reader.readLine();
if (!"quit".equals(line)) {
jedis.publish("mychannel", line); //从 mychannel 的频道上推送消息
} else {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
订阅者
public class PubSubDemo {
public static void main( String[] args )
{
// 连接redis服务端
JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "192.168.100.62", 6379, 3000, "kaiyuan");
System.out.println(String.format("redis pool is starting, redis ip %s, redis port %d", "127.0.0.1", 6379));
SubThread subThread = new SubThread(jedisPool); //订阅者
subThread.start();
Publisher publisher = new Publisher(jedisPool); //发布者
publisher.start();
// jedisPool.close();
}
}
测试类
public class SubThread extends Thread {
private final JedisPool jedisPool;
private final SubscriberListener subscriber = new SubscriberListener();
private final String channel = "mychannel";
public SubThread(JedisPool jedisPool) {
super("SubThread");
this.jedisPool = jedisPool;
}
@Override
public void run() {
System.out.println(String.format("subscribe redis, channel %s, thread will be blocked", channel));
Jedis jedis = null;
try {
jedis = jedisPool.getResource(); //取出一个连接
jedis.subscribe(subscriber, channel); //通过subscribe 的api去订阅,入参是订阅者和频道名
} catch (Exception e) {
System.out.println(String.format("subsrcibe channel error, %s", e));
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
测试结果
redis pool is starting, redis ip 127.0.0.1, redis port 6379
subscribe redis, channel mychannel, thread will be blocked
subscribe redis channel success, channel mychannel, subscribedChannels 1
mytest -------------我键入的值
receive redis published message, channel mychannel, message mytest
this is my second test -------------我键入的值
receive redis published message, channel mychannel, message this is my second test