Springboot实现redis键失效监控操作

 pom.xml文件添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 创建一个Redis消息接收器

package cn.tyrone.springboot.redis.message;
 
import java.util.concurrent.CountDownLatch;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
 
public class Receiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
 
    private CountDownLatch latch;
 
    @Autowired
    public Receiver(CountDownLatch latch) {
        this.latch = latch;
    }
 
    public void receiveMessage(String message) {
        LOGGER.info("Received <" + message + ">");
        latch.countDown();
    }
}
Receiver这是一个定义了一个接收消息的方法的类。当你把这个类作为一个消息监听器来注册后,你可以自定义消息接收的方法名。本例中采用“receiveMessage”作为接收消息的方法。

3. 注册一个监听器并发送消息

Spring Data Redis 提供了使用Redis发送和接收的消息的所有的组件。我们只需要做以下配置: 
- 一个Redis连接工厂(A connection factory) 
- 一个消息监听器的容器(A message listener container) 
- 一个Redis模板(A redis template) 
我们使用redis template发送消息,把Receiver类注册为一个消息监听器以使它可以接收消息。Connection factory是授权它们连接Redis服务的。 
本例中采用的是SpringBoot默认的RedisConnectionFactory,这是一个基于jedis Redis库的JedisConnectionFactory的实例。它被注入到消息监听器和redis模板中。

编写SpringBoot启动类并注入本例需要的对象实例

package cn.tyrone.springboot.redis.message;
 
import java.util.concurrent.CountDownLatch;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
 
//https://spring.io/guides/gs/messaging-redis/
 
@SpringBootApplication
public class Application {
    public static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
 
    /*
     * Redis消息监听器容器
     * 这个容器加载了RedisConnectionFactory和消息监听器
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, 
            MessageListenerAdapter listenerAdapter){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("sprinboot-redis-messaage"));
        return container;
    }
 
    /*
     * 将Receiver注册为一个消息监听器,并指定消息接收的方法(receiveMessage)
     * 如果不指定消息接收的方法,消息监听器会默认的寻找Receiver中的handleMessage这个方法作为消息接收的方法
     */
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver){
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
 
    /*
     * Receiver实例
     */
    @Bean
    Receiver receiver(CountDownLatch latch){
        return new Receiver(latch);
    }
 
    @Bean
    CountDownLatch latch(){
        return new CountDownLatch(1);
    }
 
    /*
     * Redis Template 用来发送消息
     */
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory){
        return new StringRedisTemplate(connectionFactory);
    }
 
    /*
     * 测试用例
     */
    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
 
        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
//      CountDownLatch latch = ctx.getBean(CountDownLatch.class);
 
        LOGGER.info("Sending message......");
        template.convertAndSend("sprinboot-redis-messaage", "Hello, SpringBoot redis message!!!!");
//      latch.wait();
 
        System.exit(0);
 
    }
 
}
对于本例并不十分清楚CountDownLatch latch这个的目的,在测试的过程中,加上这句代码,会抛一个异常,但是发送和接收消息都是成功的。异常信息如下:

2017-07-20 10:14:50.909  INFO 7200 --- [           main] c.t.s.redis.message.Application          : Sending message......
Exception in thread "main" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:502)
    at cn.tyrone.springboot.redis.message.Application.main(Application.java:77)
如果将此代码注释掉,该异常也将消息。同时,也并不影响消息的发布与接收。CountDownLatch 只是一个同步的辅助类,测试过程中,并没有发现这个类对测试结果的有什么帮助。

 

 

参考了上面案例的情况下 就很容易进行监听key失效的操作了

首先

之后将redis-service.config文件进行修改(windows为例,linux也一样)

找到notify-keyspace-events 并将notify-keyspace-events 修改为 notify-keyspace-events Ex

配置Ex对应的意思如下: E: 键事件通知,以__keysevent@<db>__为前缀   x:过期事件(每次key过期时生成)  

 

# K    键空间通知,以__keyspace@<db>__为前缀  
# E    键事件通知,以__keysevent@<db>__为前缀  
# g    del , expipre , rename 等类型无关的通用命令的通知, ...  
# $    String命令  
# l    List命令  
# s    Set命令  
# h    Hash命令  
# z    有序集合命令  
# x    过期事件(每次key过期时生成)  
# e    驱逐事件(当key在内存满了被清除时生成)  
# A    g$lshzxe的别名,因此”AKE”意味着所有的事件  
参考文献:

http://blog.csdn.net/kry1201/article/details/72629107

     上面主要是讲了利用redis的发布和订阅功能,而过期也是一种消息,也就是过期时会发布一条消息出去,而订阅的key为

以__keysevent@<db>__为前缀   x:过期事件(每次key过期时生成)

 

如:__keyevent@0__:expired,

 

也就是RedisMessageListenerContainer改为如下:

@Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, 
            MessageListenerAdapter listenerAdapter){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
       // container.addMessageListener(listenerAdapter, new PatternTopic("sprinboot-redis-messaage"));
        container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@0__:expired"));
        return container;
    }
    
     /**
     * 消息监听器适配器,绑定消息处理器,利用反射技术调用消息处理器的业务方法
     * @param redisReceiver
     * @return
     */
    @Bean
    MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) {
        System.out.println("消息适配器进来了");
        return new MessageListenerAdapter(redisReceiver, "receiveMessage");
    }
@Service
public class RedisReceiver {
    
    public void receiveMessage(String message) {
        System.out.println("消息来了:"+message);
        //这里是收到通道的消息之后执行的方法
    }
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于SpringBoot实现Redis监听器的问题,可以参考以下步骤: 1. 添加相关依赖 在pom.xml文件添加如下依赖: ``` <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 创建监听器 创建一个类,实现org.springframework.data.redis.connection.MessageListener接口,并在该类重写onMessage方法,监听Redis指定key的变化。 ``` @Component public class RedisMessageListener implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { // 监听到key的变化后,在这里实现具体的操作 } } ``` 3. 配置监听器 在Spring Boot的配置类,注入RedisMessageListener,并通过RedisConnectionFactory创建监听器容器,并指定需要监听的key。 ``` @Configuration public class RedisConfig { @Autowired private RedisMessageListener redisMessageListener; @Bean MessageListenerAdapter listenerAdapter() { return new MessageListenerAdapter(redisMessageListener); } @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter(), new PatternTopic("your_key_pattern")); return container; } } ``` 4. 测试 监听器配置完成后,可以通过RedisTemplate向指定key写入数据,验证是否能够监听到key的变化。 以上就是SpringBoot实现Redis监听器的基本步骤。如有疑问,请随时向我提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值