Redis之监听失效KEY

修改Redis配置

1. 事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发,故需要订阅 __keyevent@0__:expired 通道0表示db0,根据自己的dbindex选择合适的数字(客户端执行redis 命令。psubscribe __keyevent@*__:expired )

2. 修改 redis.conf 文件 

修改 notify-keyspace-events Ex

3. 重启redis , 即可测试失效事件的触发, 监听获取的值为 key

redis配置好后,现在来准备java测试代码

SpringConfig文件,配置listenerContainer,redisKeyExpirationListener两个bean

package com.yj.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import com.yj.listener.RedisKeyExpirationListener;

@Configuration
@ComponentScan("com.yj")
public class SpringConfig {
	@Bean
	RedisMessageListenerContainer listenerContainer(RedisConnectionFactory connectionFactory) {
		RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
		listenerContainer.setConnectionFactory(connectionFactory);
		return listenerContainer;
	}

	@Bean
	KeyExpirationEventMessageListener redisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
		return new RedisKeyExpirationListener(listenerContainer);
	}
}

RedisKeyExpirationListener文继承KeyExpirationEventMessageListener,重写onMessage回调方法

package com.yj.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
	private static final Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

	public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {
		String redisKey = message.toString();
		logger.info("即将要失效的Key:" + redisKey);
	}
}

我们往redis中插入一条expire为10秒的数据,则当key失效时,会触发监听,打印出

2018-11-09 15:04:08.209  INFO 10360 --- [enerContainer-2] c.y.listener.RedisKeyExpirationListener  : 即将要失效的Key:test

 

你可能感兴趣的:(Redis)