MessageListener通过监听key过期的Redis keyspace通知,然后通过ApplicationEventPublisher发布RedisKeyExpiredEvent事件的模式进行事件监听和广播。
redis.conf地址:https://github.com/redis/redis/blob/unstable/redis.conf
Redis官方地址:https://redis.io/topics/notifications
配置发布哪些类型的键空间通知,允许客户端订阅PUB/SUB频道:
notify-keyspace-events Ex
notify-keyspace-events选项用于配置Keyspace Notifications,即当Redis数据集发生变化时,它可以发布事件。该选项枚举值由多个字符组成,如下:
注意:
Keyspace通知是通过为影响Redis数据空间的每个操作发送两种不同类型的事件来实现的,例如,针对数据库0中名为mykey的键的DEL操作将触发两条消息的传递,这与以下两个PUBLISH命令完全等效:
PUBLISH __keyspace@0__:mykey del
PUBLISH __keyevent@0__:del mykey
第一个通道监听所有针对key为mykey的时间,另一个通道仅监听key为mykey上的del操作时间。
第一种事件在通道中有keyspace前缀,称为keyspace通知;第二种具有keyevent前缀,称为keyevent通知。
在上面的示例中,为mykey键生成了一个del事件,会产生两条消息:
可以只启用一种通知,以便只传递我们感兴趣的事件子集。
notify-keyspace-events Elg
notify-keyspace-events Ex
CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) "xE"
CONFIG SET notify-keyspace-events Eg
"OK"
org.springframework.data.redis.listener.KeyspaceEventMessageListener#init方法定义了设置notify-keyspace-events属性的方法,如果notify-keyspace-events方法不为空则不允许修改:
public void init() {
if (StringUtils.hasText(keyspaceNotificationsConfigParameter)) {
RedisConnection connection = listenerContainer.getConnectionFactory().getConnection();
try {
//获取notify-keyspace-events属性配置
Properties config = connection.getConfig("notify-keyspace-events");
//判定notify-keyspace-events属性是否有值,无值则允许修改
if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
//修改notify-keyspace-events属性
connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
}
} finally {
connection.close();
}
}
doRegister(listenerContainer);
}
开源SDK:https://github.com/mingyang66/spring-parent