redis主键过期监听
redis主键过期监听,本质就是使用redis的消息推送
编辑redis 配置文件 ,修改为 notify-keyspace-events "Ex"
注册 RedisMessageListenerContainer ,为Redis消息侦听器提供异步行为的容器
容器是必须的
//创建监听时会检查容器是否存在
public KeyspaceEventMessageListener(RedisMessageListenerContainer listenerContainer) {
Assert.notNull(listenerContainer, "RedisMessageListenerContainer to run in must not be null!");
this.listenerContainer = listenerContainer;
}
@Configuration
public class RedisConfigurer extends CachingConfigurerSupport {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
//创建监听,继承KeyExpirationEventMessageListener ,重写onMessage方法
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Autowired
private OrderItemService orderItemService;
private static Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);
@Override
public void onMessage(Message message, byte[] pattern) {
//在这里处理业务,因为时键过期,所以只能拿到键值,不能拿到value
String expiredKey = message.toString();
log.info("Redis主键过期监听" + expiredKey);
if (expiredKey.startsWith("order:")) {
log.info("Redis主键过期监听符合要求的主键" + expiredKey);
//Todo取消订单
orderItemService.updateCannelOrderByTimeOut(expiredKey);
}
}
}