首先请确保redis已经成功开启了通知功能,可参考《Redis 键空间通知》。
Springboot demo文件目录如下:
- pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- application.yml
配置redis数据库信息
spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
password:
- MessageListenerConfiguration
读取redis配置文件和开启监听
@Configuration
public class MessageListenerConfiguration {
@Bean
public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory redisConnection) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnection);
Topic topic = new PatternTopic("__keyevent@0__:*");
container.addMessageListener(new TopicMessageListener(), topic);
return container;
}
}
- TopicMessageListener
通知内容解析及后续的业务代码
public class TopicMessageListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] bytes) {
byte[] body = message.getBody();
byte[] channel = message.getChannel();
String key = new String(body);
String topic = new String(channel);
System.out.println(key);
System.out.println(topic);
//TODO:获取通知后的业务代码
}
}
然后我们启动项目,用以测试
我们在命令行中分别进行赋值和删除的操作
可以看到idea的打印结果中,出现了操作的key值和channel