zoukankan      html  css  js  c++  java
  • springboot redis 监听过期key值事件

    redis 中的key值过期后,触发通知事件

     

    1、创建springboot工程,创建监听类

     

    maven配置

    <dependencies>
            <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.10.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>1.5.10.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <version>1.5.10.RELEASE</version>
                <scope>test</scope>
            </dependency>
        </dependencies>             

    创建两个类

    RedisKeyExpirationListener
    @Component
    public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    
        public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
            super(listenerContainer);
        }
    
        /**
         * 针对redis数据失效事件,进行数据处理
         * @param message
         * @param pattern
         */
        @Override
        public void onMessage(Message message, byte[] pattern) {
            // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
            String expiredKey = message.toString();
            System.out.println(expiredKey);
        }
    }
    RedisListenerConfig
    @Configuration
    public class RedisListenerConfig {
        @Bean
        RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
    
            RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            return container;
        }
    }

    2、redis配置

     使用默认配置,localhost:6379 不设置密码 

    然后在此基础上把notify-keyspace-events Ex 这一行的注释打开

    启动工程 redis-server.exe redis.windows.conf 

    3、测试

     

    执行命令 set a 1 ex 2

    两秒后触发回调

     

     

     

  • 相关阅读:
    游戏开发之游戏策划的基本原则
    Lua游戏脚本语言入门
    游戏策划之游戏心理学理论深入浅出
    微博的10大特征包括哪些?
    普米族求助,十万火急!!! 请大家给力!!!
    剑指微博营销,速创品牌传奇
    将网络推广进行到底
    浅谈如何利用微博进行网站推广(转)
    “土风计划”,陈哲另一个伟大事业
    快速增加微博粉丝的十六大技巧
  • 原文地址:https://www.cnblogs.com/yeyongjian/p/10106168.html
Copyright © 2011-2022 走看看