Springboot + Redis:整合键消息通知

首先请确保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
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值