温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解Redis如何开启键空间通知实现超时通知

发布时间:2020-07-18 15:55:46 来源:亿速云 阅读:256 作者:小猪 栏目:数据库

小编这次要给大家分享的是详解Redis如何开启键空间通知实现超时通知,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

Redis部分设置

修改配置文件redis.conf(Windows为redis.windows.conf)

  • 打开该配置文件(位置取决于自己的安装位置),找到Event notification部分。
  • 将notify-keyspace-events Ex的注释打开或者添加该配置,其中E代表Keyevent,此种通知会返回key的名字,x代表超时事件。
  • 如果notify-keyspace-events ""配置没有被注释的话要注释掉,否则不会生效。
  • 保存后重启redis,一定要使用当前配置文件重启,例如src/redis-server redis.conf

SpringBoot部分设置

添加redis依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

在全局配置文件application中添加redis配置

spring.redis.host = 39.105.145.179
spring.redis.port=6379
spring.redis.database=0
spring.redis.listen-pattern = __keyevent@0__:expired

listen-pattern填写超时时间,意思为springboot将监听redis发出的超时键空间通知。

创建listener

public class TopicMessageListener implements MessageListener {
 @Override
 public void onMessage(Message message, byte[] bytes) {
 byte[] body = message.getBody();
 byte[] channel = message.getChannel();
 System.out.println(new String(body));
 System.out.println(new String(channel));
 }
}

其中message为redis返回的通知,body为超时的key的名字,channel为超时事件

创建listener配置类

@Configuration
public class RedisListenerConfiguration {

 @Bean
 public RedisMessageListenerContainer getListenerContainer(RedisConnectionFactory connectionFactory){
 //创建连接容器
 RedisMessageListenerContainer container = new RedisMessageListenerContainer();
 //放入redis连接
 container.setConnectionFactory(connectionFactory);
 //写入需要被监听的类型,即超时监听
 Topic topic = new PatternTopic("__keyevent@0__:expired");
 container.addMessageListener(new TopicMessageListener(), topic);
 return container;
 }
}

之后当有键值过期时,redis会发送通知被上面的TopicMessageListener接收,在该类中即可调用对应的业务方法进行业务处理。

看完这篇关于详解Redis如何开启键空间通知实现超时通知的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI