一、配置Redis开启

打开conf/redis.conf 文件,添加参数:notify-keyspace-events Ex

Redis数据失效监听_缓存

二、验证配置

  • 步骤一:进入redis客户端:redis-cli
  • 步骤二:执行 CONFIG GET notify-keyspace-events ,如果有返回值证明配置成功,如果没有执行步骤三
  • 步骤三:执行CONFIG SET notify-keyspace-events "Ex",再查看步骤二是否有值

Redis数据失效监听_数据库_02

三、两个类

package com.ciih.autopaddleGetway.config.redis;

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.RedisMessageListenerContainer;

import javax.annotation.Resource;

@Configuration
public class RedisConfig {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;
    @Resource
    private RedisKeyExpirationListener redisExpiredListener;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        //监听所有key的过期事件
        redisMessageListenerContainer.addMessageListener(redisExpiredListener, redisExpiredListener.getTopic());
        return redisMessageListenerContainer;
    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

 

package com.ciih.autopaddleGetway.config.redis;

import lombok.Data;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.stereotype.Component;

@Data
@Component
public class RedisKeyExpirationListener implements MessageListener {
    //监听的主题(只监听redis数据库1,如果要监听redis所有的库,把1替换为*)
    public final PatternTopic topic = new PatternTopic("__keyevent@1__:expired");

    /**
     * Redis失效事件 key
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiraKey = message.toString();
        System.out.println(expiraKey + "触发了失效事件!!!!");
        System.out.println();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.