工作生活

springBoot实现redis的监听

2020-03-10  本文已影响0人  jianshuqiang

业务场景:监控系统中实现对用户的用眼保护,超时提醒的问题
1、修改配置文件
notify-keyspace-events 将"" 修改成Ex
注意:只是做修改,否则出现启动时候报错的问题
编写监听的配置

package com.company.info.auth.config;

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;
@Configuration
public class RedisListenerConfig {
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

编写监听的实现

package com.company.info.auth.listener;

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;
/**
 *  @title RedisKeyExListener
 *  修改redis 的配置文件 notify-keyspace-events ("")Ex
 *  @Description 描述 监听redis中已经过期的key
 *  @author zhangqiang
 *  @Date 2019年07月04日 9:35
 *  @Copyright 2019-2020 www.epri.sgcc.com.cn All rights reserved.
 */
@Component
public class RedisKeyExListener extends KeyExpirationEventMessageListener {

    public RedisKeyExListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        System.out.println("当前key过期,请即时处理");
        System.out.println(expiredKey);
    }
}

上一篇下一篇

猜你喜欢

热点阅读