- List item
配置参数
1.首先确认liunx中安装了redis
2.修改redis的配置文件
配置键空间通知
在 Redis 配置文件(通常是 redis.conf)中,启用键空间通知配置如下:
conf
notify-keyspace-events Ex
E: 启用 Key Event 通知。
x: 启用过期事件通知。
第二步
redis:
localhost: 123.249.16.100
port: 6379
database: 7
password:
listen-pattern: __keyevent@7__:expired
这里要注意 数据库要设置7的话 listen-pattern里也要是7
这将使客户端收到 Redis 第 7 个数据库中所有过期键的通知。
赋值
redisTemplate.opsForValue().set(orderNo,"1",24, TimeUnit.SECONDS);
正常赋值
配置监听
package com.ruoyi.hospital.manager.redis;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
@Component
public class TopicMessageListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
byte[] body = message.getBody();
byte[] channel = message.getChannel();
//获取到key
String expiredKey = new String(body);
String topic = new String(channel);
System.out.println(expiredKey);
System.out.println(topic);
}
}
package com.ruoyi.hospital.manager.redis;
import org.springframework.beans.factory.annotation.Value;
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;
import org.springframework.data.redis.listener.Topic;
@Configuration
public class MessageListenerConfiguration {
@Value("${spring.redis.listen-pattern}")
public String pattern;
@Bean
public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory redisConnection){
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnection);
// 设置监听主题
Topic topic = new PatternTopic(this.pattern);
container.addMessageListener(new TopicMessageListener(), topic);
return container;
}
}
这样 当过期之后就会onMessage方法里执行了