Redis-过期键监听的应用

Redis-过期键监听的应用

1、应用场景
前期的一个项目,其中一个功能是定时控制楼宇的灯。网关走的4G无线网络,在实际运行中,不时会有一两个灯没有关掉或者打开。经过分析,由于4G网络的不稳定性比较大,断线重连时常发生,若此时正好处于服务器指令发送时间段,会导致指令无法送达。

2、当时采用的解决方案是生成冗余指令,把冗余指令放入redis,并设置过期时间。程序对过期事件进行监听,根据约定的key规则,过滤出我们需要的key,进行下一步操作

3、相关依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

4、继承MessageListenerAdapter,自定义监听器,此种方式可以在注册监听器时设置topic,对具体的一个database进行监听。

@Slf4j
@Component
public class RedisKeyExpirationListener extends MessageListenerAdapter {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        log.info("Redis监听信息:{}",key);
        if (StringUtils.isNotBlank(key)){
            if (key.startsWith("confirm_on_")){
                // 重复开确认
            }
            if (key.startsWith("confirm_off_")){
                // 重复关确认
            }
        }
    }
}

5、配置RedisMessageListenerContainer并注册监听器

@Configuration
public class RedisListenerConfig {
    @Autowired
    private RedisKeyExpirationListener redisKeyExpirationListener;
    @Value("${spring.redis.database:0}")
    private int database;

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(redisKeyExpirationListener, new PatternTopic("__keyevent@" + database + "__:expired"));
        return container;
    }
}

6、更改redis配置文件,放开注释或者添加以下内容,重启redis

notify-keyspace-events Ex

7、扩展一:继承KeyExpirationEventMessageListener的监听器,构造函数传入的是RedisMessageListenerContainer ,监听器会把自己注册进去。特别注意的是这种写法是监听所有的database,并且不能指定。TOPIC如下
private static final Topic KEYEVENT_EXPIRED_TOPIC = new PatternTopic(“keyevent@*:expired”);

@Slf4j
@Component
public class RedisKeyExpirationListener2 extends KeyExpirationEventMessageListener {
    public RedisKeyExpirationListener2(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件,进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取到失效的 key,进行业务处理
        String expiredKey = message.toString();
        log.info("监听失效key:{}",expiredKey);
    }
}

8、扩展二:redis设置相关,键空间和键事件相关,来自配置文件。

############################# 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 Ex

小尾巴~~
只要有积累,就会有进步

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值