Reputation: 194
Our application needs to listen to Redis key expired events and process the data in the key. Using RedisMessageListenerContainer I can get the expiry events but those only contain the expired key and not the key value. Hence wanted to use KeyExpirationEventMessageListener along with Redis Repository.
But am not able to configure KeyExpirationEventMessageListener and wanted some guidance for the same.
Upvotes: 2
Views: 2088
Reputation: 1454
I've done this in a bit different way, using Spring's @EventListener
.
@Slf4j
@EnableRedisRepositories(enableKeyspaceEvents = RedisKeyValueAdapter.EnableKeyspaceEvents.ON_STARTUP)
@Configuration
public class RedisListenerConfig {
@EventListener
public void handleRedisKeyExpiredEvent(RedisKeyExpiredEvent<String> event) {
String eventId = new String(event.getId());
log.info("Key {} has expired. Value {}", eventId, event.getValue());
}
}
The whole manual can be found here Baeldung.com
Working on Java 17 and Spring Boot 3.x.x as well as on Java 8 and Spring Boot 2.5.x
Upvotes: 1
Reputation: 6736
All you need to do is register an ApplicationListener
for eg. RedisKeyExpiredEvent
.
@EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)
public class Config {
@Bean
ApplicationListener<RedisKeyExpiredEvent<Person>> eventListener() {
return event -> {
System.out.println(String.format("Received expire event for key=%s with value %s.",
new String(event.getSource()), event.getValue()));
};
}
}
You can find a full sample here.
Upvotes: 2