1. 程式人生 > >SpringBoot2監聽redis過期的key

SpringBoot2監聽redis過期的key

1、修改Redis配置

把  #  notify-keyspace-events Ex 前面的註釋去掉,然後重啟redis

2、pom檔案新增

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

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<String, String> 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("
[email protected]
__: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 [[email protected]  11
11