Spring boot 2.0 對於redis的key過期觸發過期事件的監聽Demo

1、redis 對事件的監聽默認是關閉的,因爲這會消耗性能

2、開啓事件

修改redis.config 文件

############################# EVENT NOTIFICATION ##############################

# Redis can notify Pub/Sub clients about events happening in the key space.
# This feature is documented at http://redis.io/topics/notifications
#
# For instance if keyspace events notification is enabled, and a client
# performs a DEL operation on key "foo" stored in the Database 0, two
# messages will be published via Pub/Sub:
#
# PUBLISH __keyspace@0__:foo del
# PUBLISH __keyevent@0__:del foo
#
# It is possible to select the events that Redis will notify among a set
# of classes. Every class is identified by a single character:
#
#  K     Keyspace events, published with __keyspace@<db>__ prefix.
#  E     Keyevent events, published with __keyevent@<db>__ prefix.
#  g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
#  $     String commands
#  l     List commands
#  s     Set commands
#  h     Hash commands
#  z     Sorted set commands
#  x     Expired events (events generated every time a key expires)
#  e     Evicted events (events generated when a key is evicted for maxmemory)
#  A     Alias for g$lshzxe, so that the "AKE" string means all the events.
#
#  The "notify-keyspace-events" takes as argument a string that is composed
#  of zero or multiple characters. The empty string means that notifications
#  are disabled.
#
#  Example: to enable list and generic events, from the point of view of the
#           event name, use:
#
#  notify-keyspace-events Elg
#
#  Example 2: to get the stream of the expired keys subscribing to channel
#             name __keyevent@0__:expired use:
#
#  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 ""

3.有哪些事件可以監聽呢?

  • 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的失效事件。

4.下面我們開始在springboot上來實現監聽,直接上代碼


**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.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
 * 配置redis監聽事件
 * Created by lpgu on 2019/8/1.
 */
@Configuration
public class RedisConfiguration {
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(){
        RedisMessageListenerContainer redisMessageListenerContainer=new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        return redisMessageListenerContainer;
    }
    @Bean
    public KeyExpirationEventMessageListener keyExpirationEventMessageListener(){
         return new KeyExpirationEventMessageListener(this.redisMessageListenerContainer());
    }
}**



import com.jdrx.iot.beans.entry.CommandRecordPO;
import com.jdrx.iot.dao.CommandRecordDao;

import com.jdrx.iot.enums.EnumCommand;
import com.jdrx.iot.redis.dao.DeviceRedisDao;
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.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * redis的key過期監聽
 * Created by lpgu on 2019/8/1.
 */
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
    private final static Logger logger = LoggerFactory.getLogger(KeyExpiredListener.class);
  
    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //key=iot:device:command:868474043308814_b39d7fb91ef74ff6a205761b62cff0fb_aaaaaa
        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);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章