redis過(guò)期監(jiān)聽(tīng)

我的應(yīng)用場(chǎng)景:因?yàn)闃I(yè)務(wù)需求,我們會(huì)每10分鐘從kafka得到數(shù)據(jù)開(kāi)始處理,這時(shí)就會(huì)存在一種情況,如果kafka數(shù)據(jù)沒(méi)有傳遞過(guò)來(lái),我們是不是要通過(guò)一種方式知道數(shù)據(jù)沒(méi)傳遞通知我們。在這里我選用的模式是redis提供的觀察者模式。

原理:從kafka得到的數(shù)據(jù)保存到redis中,key的失效時(shí)間可以自定義配置(我定義15分鐘失效),每次從kafka得到數(shù)據(jù)都去刷新redis,這樣如果kafka每次都傳遞數(shù)據(jù),redis就不會(huì)失效,如果不傳遞數(shù)據(jù),redis就會(huì)失效,然后通過(guò)redis的監(jiān)聽(tīng)器得到這個(gè)失效的redis再進(jìn)行后續(xù)處理(我們這邊是進(jìn)行郵件報(bào)警)

1:配置redis的失效監(jiān)聽(tīng),需要修改redis.conf配置文件

增加:notify-keyspace-events "Ex"

配置文件中找到notify-keyspace-events,修改成notify-keyspace-events "Ex"

Ex 的解釋如下:

2:配置文件修改好后,重新啟動(dòng)redis,我的redis是用docker啟動(dòng)的。重新啟動(dòng)了容器。

3:驗(yàn)證redis失效監(jiān)聽(tīng)是否好用。

進(jìn)入redis容器:

docker exec -it redis /bin/sh

運(yùn)行redis客戶端:

redis-cli

運(yùn)行監(jiān)聽(tīng)命令:

psubscribe __keyevent@0__:expired

再啟動(dòng)一個(gè)redis-cli

創(chuàng)建一個(gè)10秒后失效的reids:

setex test 10 test

10秒后,可以看到監(jiān)聽(tīng)端口可以接收到失效的redis的key.

4:java代碼編寫(xiě),pom.xml引入

<dependency>

????<groupId>org.springframework.boot</groupId>

????<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

5:配置redis的config,配置了兩種方式,第一種方式是支持@Cacheable創(chuàng)建redis.第二種方式是直接引用redis提供的StringRedisTemplate類(lèi)來(lái)調(diào)用redis的set和get方法。

第一種方式的配置文件寫(xiě)法:RedisCacheConfig.java

@Configuration

public class RedisCacheConfig{

@Bean

? ? public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {

? ? ? ? return new RedisCacheManager(

? ? ? ? ? ? ? ? RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory),

? ? ? ? ? ? ? ? this.getRedisCacheConfigurationBase(), // 默認(rèn)策略

? ? ? ? ? ? ? ? this.getRedisCacheConfigurationMap() // 指定 key 策略

? ? ? ? );

}

private RedisSerializer<String> keySerializer() {

? ? ? ? return new StringRedisSerializer();

}

private RedisSerializer<Object> valueSerializer() {

? ? ? ? return new GenericJackson2JsonRedisSerializer();

}

private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {

? ? ? ? Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();

? ? ? ? redisCacheConfigurationMap.put("NoDataCache0", this.getRedisCacheConfigurationWithTtl(60));

? ? ? ? return redisCacheConfigurationMap;

? ? }

private RedisCacheConfiguration getRedisCacheConfigurationBase() {

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

? ? ? ? ? ? ? ? //.entryTtl(this.timeToLive)? --定義到期時(shí)間

? ? ? ? ? ? ? ? .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))

? ? ? ? ? ? ? ? .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));

? ? ? ? ? ? ? ? //.disableCachingNullValues(); //保存的數(shù)據(jù)不能為null

? ? ? ? return config;

? ? }

private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {

? ? ? ? RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

? ? ? ? ? ? ? ? .entryTtl(Duration.ofSeconds(seconds))? //定義到期時(shí)間

? ? ? ? ? ? ? ? .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))

? ? ? ? ? ? ? ? .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));

? ? ? ? ? ? ? ? //.disableCachingNullValues(); //保存的數(shù)據(jù)不能為null

? ? ? ? return config;

? ? }

}

用RedisCacheManager的構(gòu)造方法來(lái)實(shí)現(xiàn),我定義了一個(gè)60秒失效的策略,redis的寫(xiě)法如下:

@Cacheable(value = "NoDataCache0" key="'rc_alarmrule_2_'+#tenantId+'_'+#metricSpecId")

public List<AlarmRuleRedisAllVO> getAlarmRuleAllRedis(long tenantId,long metricSpecId) {

return null;

}

1)value = "NoDataCache0" 是我策略里定義的名稱(chēng)redisCacheConfigurationMap.put("NoDataCache0", this.getRedisCacheConfigurationWithTtl(60));

這個(gè)可以定義多個(gè)。每個(gè)的名稱(chēng)和失效時(shí)間配置不一樣。

2)這種方式的配置,失效時(shí)間只能寫(xiě)在配置文件中或者寫(xiě)死,如果我想按照我表中定義一個(gè)失效時(shí)間實(shí)時(shí)的進(jìn)行變化就做不到了。所以我又用了第二種配置方案。

第二種方式的配置文件寫(xiě)法:RedisCacheConfig.java

@Service

public class RedisService {

? ? @Autowired

? ? private StringRedisTemplate redisTemplate;

? ? /**

? ? * 永久

? ? * @param key

? ? * @param value

? ? */

? ? public void set(String key, Object value) {

? ? ? ? redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value));

? ? }

? ? /**

? ? * 將 key,value 存放到redis數(shù)據(jù)庫(kù)中,設(shè)置過(guò)期時(shí)間單位是秒

? ? * @param key

? ? * @param value

? ? * @param timeout

? ? */

? ? public void setBySeconds(String key, Object value, long timeout) {

? ? ? ? redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value), timeout, TimeUnit.SECONDS);

? ? }

? ? /**

? ? * 將 key,value 存放到redis數(shù)據(jù)庫(kù)中,設(shè)置過(guò)期時(shí)間單位是分鐘

? ? * @param key

? ? * @param value

? ? */

? ? public void setByMinutes(String key, Object value, long timeout) {

? ? ? ? redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value), timeout, TimeUnit.MINUTES);

? ? }

? ? /**

? ? * 將 key,value 存放到redis數(shù)據(jù)庫(kù)中,設(shè)置過(guò)期時(shí)間單位是小時(shí)

? ? * @param key

? ? * @param value

? ? */

? ? public void setByHours(String key, Object value, long timeout) {

? ? ? ? redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value), timeout, TimeUnit.HOURS);

? ? }

? ? /**

? ? * 將 key,value 存放到redis數(shù)據(jù)庫(kù)中,設(shè)置過(guò)期時(shí)間單位是天

? ? * @param key

? ? * @param value

? ? */

? ? public void setByDays(String key, Object value, long timeout) {

? ? ? ? redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value), timeout, TimeUnit.DAYS);

? ? }

? ? /**

? ? * 刪除 key 對(duì)應(yīng)的 value

? ? * @param key

? ? */

? ? public void delete(String key) {

? ? ? ? redisTemplate.delete(key);

? ? }

? ? /**

? ? * 獲取與 key 對(duì)應(yīng)的對(duì)象

? ? * @param key

? ? * @param clazz 目標(biāo)對(duì)象類(lèi)型

? ? * @param <T>

? ? * @return

? ? */

? ? public <T> T get(String key, Class<T> clazz) {

? ? ? ? String s = get(key);

? ? ? ? if (s == null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? return JsonUtil.convertString2Obj(s, clazz);

? ? }

? ? /**

? ? * 獲取與 key 對(duì)應(yīng)的對(duì)象

? ? * @param key

? ? * @param clazz 目標(biāo)對(duì)象類(lèi)型

? ? * @param <T>

? ? * @return

? ? * @throws IOException

? ? * @throws JsonMappingException

? ? * @throws JsonParseException

? ? */

? ? public <T> List<T> getList(String key, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {

? ? ? ? String s = get(key);

? ? ? ? if (s == null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? return JsonUtil.toList(s,clazz);

? ? }

? ? /**

? ? * 獲取 key 對(duì)應(yīng)的字符串

? ? * @param key

? ? * @return

? ? */

? ? public String get(String key) {

? ? ? ? return redisTemplate.opsForValue().get(key);

? ? }

? ? /**

? ? * 查詢 key 對(duì)應(yīng)的過(guò)期時(shí)間

? ? * @param key

? ? * @return

? ? */

? ? public String getExpire(String key){

? ? ? ? Long timeout = redisTemplate.getExpire(key,TimeUnit.MILLISECONDS);

? ? ? ? System.out.println(timeout);

? ? ? ? if (timeout < 0)

? ? ? ? ? ? return "Has expired!";

? ? ? ? Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() + timeout;

? ? ? ? return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.ofInstant(

? ? ? ? ? ? ? ? Instant.ofEpochMilli(milliSecond),ZoneId.systemDefault()));

? ? }

? ? /**

? ? * 判斷 key 是否在 redis 數(shù)據(jù)庫(kù)中

? ? * @param key

? ? * @return

? ? */

? ? public boolean exists(final String key) {

? ? ? ? return redisTemplate.hasKey(key);

? ? }

這種方式可以實(shí)時(shí)的改變r(jià)edis的失效時(shí)間。

6:配置redis失效的監(jiān)聽(tīng)config??RedisListenerConfig.java

@Configuration

public class RedisListenerConfig {

? ? @Bean

? ? RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

? ? ? ? RedisMessageListenerContainer container = new RedisMessageListenerContainer();

? ? ? ? container.setConnectionFactory(connectionFactory);

//? ? ? ? container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@0__:expired"));

? ? ? ? return container;

? ? }

}

我沒(méi)有配置__keyevent@0__:expired",對(duì)某個(gè)db進(jìn)行監(jiān)聽(tīng),RedisMessageListenerContainer有個(gè)默認(rèn)的配置是對(duì)所有的db進(jìn)行監(jiān)聽(tīng)。

7:redis的監(jiān)聽(tīng)類(lèi)?RedisKeyExpirationListener.java

@Component

public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

? ? public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {

? ? ? ? super(listenerContainer);

? ? }

? ? /**

? ? * 針對(duì)redis數(shù)據(jù)失效事件,進(jìn)行數(shù)據(jù)處理

? ? * @param message

? ? * @param pattern

? ? */

@Override

? ? public void onMessage(Message message, byte[] pattern) {

? ? ? ? //message.toString()可以獲取失效的key

? ? ? ? String expiredKey = message.toString();

? ? ? ? logger.debug("失效的redis是:"+expiredKey);

? ? ? ? String part = "NoDataCache0";

? ? ? ? //如果是NoDataCache0:開(kāi)頭的key,進(jìn)行處理

? ? ? ? if(expiredKey.startsWith(part)){

? ? ? ? ? ? ? ? //自己的業(yè)務(wù)邏輯

? ? ? ? }

}

1)注意:失效的redis只能得到key,是得不到value的,所以業(yè)務(wù)邏輯如果用到value里的值需要把值寫(xiě)到key中。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容