当前位置: 移动技术网 > IT编程>数据库>Redis > Redis开启键空间通知实现超时通知的步骤详解

Redis开启键空间通知实现超时通知的步骤详解

2020年06月14日  | 移动技术网IT编程  | 我要评论

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开启键空间通知实现超时通知的步骤的文章就介绍到这了,更多相关redis键空间通知内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网