SpringBoot2监听redis过期的key

1、修改Redis配置

把  #  notify-keyspace-events Ex 前面的注释去掉,然后重启redis

注意 Ex要加双引号

2、pom文件添加

       
            org.springframework.boot
            spring-boot-starter-data-redis
        

3、添加redis监听

package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisMessageListener implements MessageListener {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    //key 过期时调用
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("onPMessage pattern " + pattern + " " + " " + message);
        String channel = new String(message.getChannel());
        String str = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        System.out.println(str);

    }


}

4、配置redis监听key过期事件

package com.example.demo.redis;

import com.example.demo.DemoApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
//value 是启动类
@Import( value = DemoApplication.class )
public class PubsubConfiguration  {

    @Autowired
    private RedisMessageListener redisMessageListener;


    @Bean
    public ChannelTopic expiredTopic() {
        return new ChannelTopic("__keyevent@0__:expired");
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            @Autowired RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        redisMessageListenerContainer.addMessageListener(redisMessageListener, expiredTopic());
        return redisMessageListenerContainer;
    }


}

4、经测试添加key=11,当其过期时,打印效果如下

 

onPMessage pattern [B@20d980fd  11
11

 

你可能感兴趣的:(Redis,SpringBoot)