开发者

spring boot redis中的key失效监听的问题解决

1、spring boot连接配置Redis参考这篇文章

https://www.jb51.net/program/339977yti.htm

2、首先开启redis的事件失效推送功能,如果是redis容器启动,参考下面的方式启动容器

docker run --restart=always -itd --name redis -p 6379:6379 redis redis-server --notify-keyspace-events Ex --requirepass xxxxxx

然后在redis客户端下面使用如下方式验证

CONFIG GET notify-keyspace-events

3、在spring boot 中新建服务类RedisKeyExpirationListener,用于捕捉获取redis中的key失效

package com.example.redis_sub.config;

import lombok.extern.slf4j.Slf4j;
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;

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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        System.out.println("key失效");
        StBEzrQMfRGring expiredKey = message.toString();
        System.out.println(expiredKey);
        System.out.println(new String(pattern));
        //业务逻http://www.devze.com辑

    }
}

4、新建配置类RedisConfig

package com.example.redis_sub.config;

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.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisConfig {

    @Bean
    RedisMessageListenerContainephpr container(RedisConnectionFactory connectionFactory) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        androidcontainer.setConnectionFactory(cophpnnectionFactory);
        // 事件以__keyevent@<db>__为前缀进行发布
//        container.addMessageListener(new RedisKeyExpirationListener(container), new PatternTopic("__keyevent@0__" +
//                ":expired"));
        container.addMessageListener(new RedisKeyExpirationListener(container), new PatternTopic("__keyevent@0__" +
                ":expired"));
        return container;
    }


}

 到此这篇关于spring boot redis中的key失效监听的问题解决的文章就介绍到这了,更多相关springboot redis key失效内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜