有时需要监听Redis的事件从而在Redis事件发生时添加一些后续操作;在实际开发过程中,有这么一个需求,监听Redis中的键状态,从而去更改程序中数据的状态;实现方法如下:
-
方法一: 实现redis提供的MessageListener接口
首先开启Redis的监听事件,大约在Redis配置文件的889行,或者直接搜索notify-keyspace-events,将其更改为你需要监听的类型
这段注释已经写得非常清楚了,建议想了解配置详情的哥们可以把下面这部分注释复制粘贴到翻译软件中自己理解,如果急于功能实现的话,那么就把notify-keyspace-events属性设置为EA
# Redis can notify Pub/Sub clients about events happening in the key space. # This feature is documented at http://redis.io/topics/notifications # # For instance if keyspace events notification is enabled, and a client # performs a DEL operation on key "foo" stored in the Database 0, two # messages will be published via Pub/Sub: # # PUBLISH __keyspace@0__:foo del # PUBLISH __keyevent@0__:del foo # # It is possible to select the events that Redis will notify among a set # of classes. Every class is identified by a single character: # # 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. # # The "notify-keyspace-events" takes as argument a string that is composed # of zero or multiple characters. The empty string means that notifications # are disabled. # # Example: to enable list and generic events, from the point of view of the # event name, use: # # notify-keyspace-events Elg # # Example 2: to get the stream of the expired keys subscribing to channel # name __keyevent@0__:expired use: # notify-keyspace-events EA # # By default all notifications are disabled because most users don't need # this feature and the feature has some overhead. Note that if you don't # specify at least one of K or E, no events will be delivered. # notify-keyspace-events ""
其次需要实现MessageListener接口
@Component @Slf4j public class MyMessageListener implements MessageListener{ @Override public void onMessage(Message message, byte[] bytes) { log.debug("键值{}",message.toString()); } }
然后需要在配置类中将这个事件监听添加到Redis容器中
@Configuration public class Configurer