SpringBoot 监听 Redis 的 Key 过期事件

叙述

在一些业务场景中,我们希望在Redis的key过期时,得到通知。

解决方案

Redis的配置

  • 修改conf文件
  • notify-keyspace-events "Ex"
  • 该配置表示监听key的过期事件,默认未开启
  • 该配置的其他信息(可以监听N多事件),可以参阅配置文件的注释,非常详细

自定义监听器

该监听器会在key过期时候触发

import java.nio.charset.StandardCharsets;

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 KeyExpiredListener extends KeyExpirationEventMessageListener {

	private static final Logger LOGGER = LoggerFactory.getLogger(KeyExpiredListener.class);

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

	@Override
	public void onMessage(Message message, byte[] pattern) {
		String channel = new String(message.getChannel(),StandardCharsets.UTF_8);
		//过期的key
		String key = new String(message.getBody(),StandardCharsets.UTF_8);
		LOGGER.info("redis key 过期:pattern={},channel={},key={}",new String(pattern),channel,key);
	}
}

@Confiugration配置

import org.springframework.beans.factory.annotation.Autowired;
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;

import io.javaweb.redis.listener.KeyExpiredListener;

@Configuration
public class RedisConfiguration {
 
	@Autowired 
	private RedisConnectionFactory redisConnectionFactory;
	
	@Bean
	public RedisMessageListenerContainer redisMessageListenerContainer() {
		RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
		redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
		return redisMessageListenerContainer;
	}
	
	@Bean
	public KeyExpiredListener keyExpiredListener() {
		return new KeyExpiredListener(this.redisMessageListenerContainer());
	}
}

往Redis写入一个key,并且设置过期时间

SpringBoot 监听 Redis 的 Key 过期事件

过期事件被触发

SpringBoot 监听 Redis 的 Key 过期事件

上一篇:Maven整合Spring,Spring mvc4.1.6,Hibernate4.3.10项目搭建总结


下一篇:org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘‘