本篇文章小编给大家分享一下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依赖
org.springframework.boot spring-boot-starter-data-redis
在全局配置文件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接收,在该类中即可调用对应的业务方法进行业务处理。
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级