redis key過時事件實現過時提醒

redis默認關閉,不建議開啓。本文提供參考。鍵空間通知一般是不啓用的,由於這個過程會產生額外消耗。java

一、開啓redis配置

#
#  notify-keyspace-events Ex
#
#  By default all notifications are disabled because most users don't need
#  this feature and the feature has some overhead. Note that if you don't
#  specify at least one of K or E, no events will be delivered.
notify-keyspace-events "Ex"
字符 發送通知
K 鍵空間通知,全部通知以 keyspace@ 爲前綴,針對Key
E 鍵事件通知,全部通知以 keyevent@ 爲前綴,針對event
g DEL 、 EXPIRE 、 RENAME 等類型無關的通用命令的通知
$ 字符串命令的通知
l 列表命令的通知
s 集合命令的通知
h 哈希命令的通知
z 有序集合命令的通知
x 過時事件:每當有過時鍵被刪除時發送
e 驅逐(evict)事件:每當有鍵由於 maxmemory 政策而被刪除時發送
A 參數 g$lshzxe 的別名,至關因而All

    輸入的參數中至少要有一個 K 或者 E , 不然的話, 無論其他的參數是什麼, 都不會有任何通知被分發。上表中斜體的部分爲通用的操做或者事件,而黑體則表示特定數據類型的操做。例如,「Kx」表示想監控某個Key的失效事件。web

二、java實現

2.1 pom配置

    spring boot2的配置redis

<dependencies>
	<!-- spring boot -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
	<!--spring2.0集成redis所需common-pool2 -->
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-pool2</artifactId>
	</dependency>
</dependencies>

2.2 配置

import java.lang.reflect.Method;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.pro.constant.ChannelConstant;
import com.spring.pro.listener.KeyExpiredListener;
import com.spring.pro.listener.UserMsgListener;

/**
 * 緩存管理(註解用)
 * @ClassName: CacheService
 * @Description:
 * @author ybw
 * @date 2017年4月20日 下午5:44:52
 */
@Configuration
@EnableCaching // 啓動緩存
public class CacheConfig extends CachingConfigurerSupport {

	/**
	 * 生成key的策略
	 * @return
	 */
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}

	/**
	 * 管理緩存
	 * @param redisTemplate
	 * @return
	 */
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
				.fromConnectionFactory(redisConnectionFactory);
		return builder.build();
	}

	/**
	 * RedisTemplate配置
	 * @param factory
	 * @return
	 */
	@Bean
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		StringRedisTemplate template = new StringRedisTemplate(factory);
		// 使用Jackson庫將對象序列化爲JSON字符串
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
				Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		template.setValueSerializer(jackson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}

	// --------------------------pub/sub-----------------------------------------
	@Resource
	private KeyExpiredListener keyExpiredListener;

		
	@Bean
	public ChannelTopic expiredTopic() {
		return new ChannelTopic(ChannelConstant.expired);
	}

	@Bean
	public RedisMessageListenerContainer redisMessageListenerContainer(
			@Autowired RedisConnectionFactory redisConnectionFactory) {
		RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
		redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
		redisMessageListenerContainer.addMessageListener(keyExpiredListener, expiredTopic());
		return redisMessageListenerContainer;
	}
	// --------------------------pub/sub end------------------------------------------
}

三、監聽

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * @Title: KeyExpiredListener.java
 * @Package com.spring.pro.listener
 * @Description:
 * @author ybwei
 * @date 2018年8月13日 下午3:54:41
 * @version V1.0
 */
@Component
public class KeyExpiredListener implements MessageListener {

	private final static Logger LOG = LoggerFactory.getLogger(UserMsgListener.class);
	@Autowired
	private RedisTemplate<?, ?> redisTemplate;

	@Override
	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());
		LOG.info("received message channel {}, body is {}.", channel, str);
	}

}

四、測試

set aa bb
expire aa 2 #設置失效時間2秒

    aa失效後,便可獲得通知。spring

相關文章
相關標籤/搜索