锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. JAVA
  4. redis监听过期key时间

redis监听过期key时间

0
  • JAVA
  • 发布于 2024-09-25
  • 0 次阅读
黄健
黄健

说明
redis key过期监听通知一定要 开启key过期通知功能。

事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发,故需要订阅 keyevent@0:expired 这个topic通道

解释:keyevent@2 :expired
__keyevent 必须以此开头;
@2 表示监听第二个数据库;
:expired 表示过期事件

1、redis 开启key过期通知

1、修改 redis.conf 文件 ,编辑/etc/redis/redis.conf文件,添加或启用以下内容(过期通知):
配置详解:

| 字符 | 发送通知 |
|—-|—————————————-|
| K | 键空间通知,所有通知以 keyspace@ 为前缀,针对Key |
| E | 键事件通知,所有通知以 keyevent@ 为前缀,针对event |
| g | DEL 、 EXPIRE 、 RENAME 等类型无关的通用命令的通知 |
| $ | 字符串命令的通知 |
| l | 列表命令的通知 |
| s | 集合命令的通知 |
| h | 哈希命令的通知 |
| z | 有序集合命令的通知 |
| x | 过期事件:每当有过期键被删除时发送 |
| e | 驱逐(evict)事件:每当有键因为 maxmemory 政策而被删除时发送 |
| A | 参数 g$lshzxe 的别名,相当于是All |

将 notify-keyspace-events ""改为 notify-keyspace-events "Ex"

然后、重启redis , 即可测试失效事件的触发, 监听获取的值为 key
2、或者登陆redis-cli之后,输入以下命令:
config set notify-keyspace-events Ex

需要的jar包

                <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.4.RELEASE</version>
        </dependency>

配置文件

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       ......
       default-lazy-init="false">

    <context:property-placeholder location="classpath:redis.properties"
                                  ignore-unresolvable="true"/>
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="1000"/>
        <property name="minIdle" value="1000"/>
        <property name="maxTotal" value="100"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
    </bean>

    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="127.0.0.1"
          p:port="6379"
          p:pool-config-ref="jedisPoolConfig"
          p:use-pool="true"
          p:database="${redis.database}"/>

    <bean id="RedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connection-factory-ref="jedisConnectionFactory"
          p:keySerializer-ref="stringRedisSerializer"
          p:valueSerializer-ref="JdkSerializationRedisSerializer"/>

    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    <bean id="JdkSerializationRedisSerializer"
          class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>

    <bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
        <constructor-arg>
            <bean class="com.mmall.concurrency.listener.RedisKeyExpiredListener"/>
        </constructor-arg>
    </bean>
    <bean id="redisContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="messageListeners">
            <map>
                <entry key-ref="messageListener">
                    <list>
<!--                        <bean class="org.springframework.data.redis.listener.ChannelTopic">-->
<!--                            <constructor-arg value="__keyevent@1__:expired" />-->
<!--                        </bean>-->
<!--                        <bean class="org.springframework.data.redis.listener.PatternTopic">-->
<!--                            <constructor-arg value="*" />-->
<!--                        </bean>-->
<!--                        <bean class="org.springframework.data.redis.listener.PatternTopic">-->
<!--                            <constructor-arg value="'__key*__:*" />-->
<!--                        </bean>-->
                        <bean class="org.springframework.data.redis.listener.ChannelTopic">
                            <constructor-arg value="__keyevent@2__:expired"/>
                        </bean>
                    </list>
                </entry>
            </map>
        </property>
    </bean>
</beans>
```java

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;


/**
 * redis监听
 * 监听类需要实现MessageListener,监听到redis key过期的时候会自动执行到onMessage方法
 * @version 1.0
 */
@Slf4j
public class RedisKeyExpiredListener implements MessageListener {

    private static final String FAIL_KEY = "fail:key";

    @Autowired
    private TestService testService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String expiredKey = message.toString();// 获取失效的key
        log.info("=========>失效的key:{}", expiredKey);
        if (expiredKey.startsWith(FAIL_KEY )) {
            // 进行相应的业务处理....
        }
    }
}

上面就可以完成监听的功能!!!!

上面的代码还可以改写成下面的形式

@Component(value ="SERVICE_NAME")
@Slf4j
public class RedisKeyExpiredListener implements MessageListener {

    private static final String FAIL_KEY = "fail:key";

    @Autowired
    private TestService testService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String expiredKey = message.toString();// 获取失效的key
        log.info("=========>失效的key:{}", expiredKey);
        if (expiredKey.startsWith(FAIL_KEY )) {
            // 进行相应的业务处理....
        }
    }
}



import com.mmall.concurrency.listener.RedisKeyExpiredListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * redis监听容器
 * @author 12706
 */
@Configuration
public class RedisConfig {

    @Autowired
    @Qualifier(value = "SERVICE_NAME")//指定的是自己写的RedisMessageListener
    private RedisKeyExpiredListener redisKeyExpiredListener;

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisMessageListenerContainer container(MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisTemplate.getConnectionFactory());
        container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@0__:expired"));
        //这里是监听redis第一个库里面key的过期
        return container;
    }

    @Bean
    public MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter(redisKeyExpiredListener);
    }
}

原文链接: https://onlyou.blog.csdn.net//article/details/103538926

标签: #JAVA 991 #redis 48 #工具 45
相关文章

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

SpringBoot整合异步任务执行 2024-10-08 11:24

同步任务: 同步任务是在单线程中按顺序执行,每次只有一个任务在执行,不会引发线程安全和数据一致性等 并发问题 同步任务需要等待任务执行完成后才能执行下一个任务,无法同时处理多个任务,响应慢,影响用 户体验 异步任务: 异步任务是在多线程中同时执行,多个任务可以并发执行,同时处理多个请求,响应快,资源

springboot kafka多数据源,通过配置动态加载发送者和消费者 2024-10-08 11:24

前言 最近做项目,需要支持kafka多数据源,实际上我们也可以通过代码固定写死多套kafka集群逻辑,但是如果需要不修改代码扩展呢,因为kafka本身不处理额外逻辑,只是起到削峰,和数据的传递,那么就需要对架构做一定的设计了。 准备test kafka本身非常容易上手,如果我们需要单元测试,引入ja

SpringBoot 集成 Redis 2024-10-08 11:24

一:SpringBoot 集成 Redis ①Redis是一个 NoSQL(not only)数据库, 常作用缓存 Cache 使用。 ②Redis是一个中间件、是一个独立的服务器;常用的数据类型: string , hash ,set ,zset , list ③通过Redis客户端可以使用多种语

SpringBoot整合QQ邮箱 2024-10-08 11:24

SpringBoot可以通过导入依赖的方式集成多种技术,这当然少不了我们常用的邮箱,现在本章演示SpringBoot整合QQ邮箱发送邮件…. 下面按步骤进行: 1.获取QQ邮箱授权码 1.1 登录QQ邮箱 1.2 开启SMTP服务 找到下图中的SMTP服务区域,如果当前账号未开启的话自己手动开启。

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.