springboot下redis过期回调示例

2020-12-22  本文已影响0人  haiyong6

springboot整合redis这里就省略,可以参考之前写过的一篇:springboot连接redis

修改redis.conf文件

redis过期回调默认在配置文件里是关闭的,因为这会一定程度上影响redis的性能,需要的时候需要手动开启:
在 redis安装包下 redis.conf 配置文件里面找到 # notify-keyspace-events Ex 去掉注释,然后重启redis.

新建RedisConfiguration类

package com.zhaohy.app.config;

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

@Configuration
public class RedisConfiguration {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public ChannelTopic expiredTopic() {
        return new ChannelTopic("__keyevent@0__:expired");  // 选择0号数据库
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        return redisMessageListenerContainer;
    }
}

新建RedisKeyExpirationListener继承org.springframework.data.redis.listener.KeyExpirationEventMessageListener监听器

package com.zhaohy.app.sys.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

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

    @Autowired
    StringRedisTemplate redisTemplate;
    
    public void onMessage(Message message, byte[] pattern) {

        String expireKey = message.toString();
        //System.out.println(expireKey);
        if (expireKey.startsWith("iov:test:")){
            System.out.println("expireKey过期了===" + expireKey);
        }
    }
}

测试:

controller里新建RedisKeyExpirationListenerTest

@RequestMapping("/test/RedisKeyExpirationListenerTest.do")
    public void RedisKeyExpirationListenerTest(HttpServletRequest request) {
        redisTemplate.opsForValue().set("iov:test:testKey1", "myTestKey1", 5, TimeUnit.SECONDS);
    }

浏览器访问此接口5秒钟后可以看到控制台输出如下,回调成功了:

expireKey过期了===iov:test:testKey1

利用此回调可以实现一些订单过期的时候恢复库存的操作,以后有空写一篇秒杀系统的实现示例。

上一篇下一篇

猜你喜欢

热点阅读