SpringBoot 2はredisの期限切れのkeyを傍受する

2803 ワード

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