场景
Spring boot
实现监听Redis key
失效事件可应对某些场景例如:处理订单过期自动取消、用户会员到期…
开启Redis键过期回调通知
Redis
默认是没有开启键过期监听功能的,需要手动在配置文件中修改。
Linux
操作系统- 修改
redis
安装目录下的redis.conf
配置文件,然后找到notify-keyspace-events Ex
这行代码,默认是注释掉的,取消注释即可(即删除掉前面的#)。 - 也有一种情况是没有这一行的,这种情况下直接把这一行添加上去即可。
- 然后重启
redis
。
- 修改
Windows
操作系统- 在安装目录下找到
redis.windows.conf
和redis.windows-service.conf
两个文件,然后分别修改这两个文件中的notify-keyspace-events Ex
字段,取消注释即可。 - 然后重启
redis
,Windows
重启命令为redis-server.exe --service-start
。
- 在安装目录下找到
Java代码实现监听回调
添加Redis键过期监听配置
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.RedisMessageListenerContainer;
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
创建监听类
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;
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
/**
* 使用该方法监听,当Redis的key失效的时候执行该方法
* @param message message must not be {@literal null}.
* @param pattern pattern matching the channel (if specified) - can be {@literal null}.
*/
@Override
public void onMessage(Message message, byte[] pattern) {
// 过期的Key
String expiraKey = message.toString();
System.out.println("该Key已失效:"+expiraKey);
}
}
指定
Redis
的key
设置值及其过期时间
Redis Setex
命令为指定的 key
设置值及其过期时间。如果 key
已经存在, SETEX
命令将会替换旧的值。