zoukankan      html  css  js  c++  java
  • springboot redis监控失效key

    1.引入依赖

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

    2.创建超时监听

    package com.jeesite.modules.test.RedisManage;
    
    import org.springframework.data.redis.connection.Message;
    import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
    import org.springframework.data.redis.listener.RedisMessageListenerContainer;
    import org.springframework.stereotype.Component;
    
    /**
     * redis失效key监听
     *
     * @author 郑文
     *
     */
    @Component
    public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
        public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
            super(listenerContainer);
        }
    
        /**
         * redis失效key事件处理
         * @param message
         * @param pattern
         */
        @Override
        public void onMessage(Message message, byte[] pattern) {
            // message.toString()可以获取失效的key
            String expiredKey = message.toString();
            System.out.println("-------------------");
            System.out.println("失效key:"+message.getBody());
        }
    }
    View Code

    3.超时监听配置

    package com.jeesite.modules.test.RedisManage;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.listener.PatternTopic;
    import org.springframework.data.redis.listener.RedisMessageListenerContainer;
    
    
    @Configuration
    public class RedisListenerConfig {
        @Bean
        RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
    
            RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            //下面这种方式是灵活配置,针对每个库的失效key做处理
            //container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@0__:expired"));
            return container;
        }
    }
    View Code

    4. controller里接口调用

       @Autowired
        public RedisTemplate redisTemplate;
        @GetMapping("/set")
        public String set() {
            redisTemplate.opsForValue().set("name", "tom"+System.currentTimeMillis(), 10, TimeUnit.SECONDS);
            return  redisTemplate.opsForValue().get("name").toString();
        }
    View Code

    5.10秒后控制台打印超时key

  • 相关阅读:
    程序的本质复杂性和元语言抽象
    编译器词法消歧设计
    关于分工的思考 (Thoughts on Division of Labor)
    数据即代码
    类型的本质和函数式实现
    二叉树迭代器算法
    kvm虚拟化存储管理
    kvm网络虚拟化管理
    kvm虚拟机的四种网络模式
    Linux 中交换空间 (swap)应该分多大才好?
  • 原文地址:https://www.cnblogs.com/tiancai/p/13161533.html
Copyright © 2011-2022 走看看